为什么不std :: getline阻止? [英] Why doesn't std::getline block?

查看:150
本文介绍了为什么不std :: getline阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Objective-C类中有一个代码(在Objective-C ++文件中):

I have this code in an Objective-C class (in an Objective-C++ file):

+(NSString *)readString
{
    string res;
    std::getline(cin, res);
    return [NSString stringWithCString:res.c_str() encoding:NSASCIIStringEncoding];
}



当我运行它,我得到一个零长度的字符串,每次。从来没有给出在命令行输入的机会。没有。当我将此代码逐字复制到 main(),它工作。我在构建设置下有ARC。我不知道它是怎么回事。 OSX 10.7.4,Xcode 4.3.2。

When I run it, I get a zero-length string, Every time. Never given the chance to type at the command line. Nothing. When I copy this code verbatim into main(), it works. I have ARC on under Build Settings. I have no clue what it going on. OSX 10.7.4, Xcode 4.3.2.

推荐答案

这意味着有输入等待在输入上读取。您可以清空输入:

It means there is input waiting to be read on the input. You can empty the input:

cin.ignore(std::numeric_limits<std::streamsize>::max();
std::getline(cin, res);

上面的代码将在尝试读取更多内容之前删除任何用户输入。

If this is happening it means you did not read all the data off the input stream in a previous read. The above code will trash any user input before trying to read more.

这可能意味着你是混合 operator>> 与 std :: getline()用于读取用户输入。在你的应用程序中使用(std :: getline())(你可以混合它们,你只需要更小心,删除'\\\
'后使用operator >>确保任何后续std :: getline()不会混淆。

This probably means that you are mixing operator>> with std::getline() for reading user input. You should probably pick one technique and use that (std::getline()) throughout your application ( you can mix them you just have to be more careful and remove the '\n' after using operator>> to make sure any subsequent std::getline() is not confused..

如果您想读取一个数字,请读取该行,然后解析该行的数字:

If you want to read a number read the line then parse the number out of the line:

std::getline(cin, line);
std::stringstream  linestream(line);

linestream >> value;

这篇关于为什么不std :: getline阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆