Mar*_*ork 109
我更喜欢C版本的C++大小限制:
// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())
// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Run Code Online (Sandbox Code Playgroud)
Eva*_*ran 95
可能是:
std::cin.ignore(INT_MAX);
Run Code Online (Sandbox Code Playgroud)
这将读入并忽略所有内容,直到EOF
.(你也可以提供第二个参数,它是要读取的字符(例如:'\n'
忽略一行).
另外:你可能想要做一个:std::cin.clear();
在此之前也要重置流状态.
jyg*_*ath 23
cin.clear();
fflush(stdin);
Run Code Online (Sandbox Code Playgroud)
从控制台读取时,这是唯一对我有用的东西.在其他每种情况下,由于缺少\n,它会无限期地读取,或者某些东西会保留在缓冲区中.
编辑:我发现以前的解决方案使事情变得更糟.然而,这个工作:
cin.getline(temp, STRLEN);
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*Ben 10
我找到了两个解决方案.
第一个,也是最简单的是使用std::getline()
例如:
std::getline(std::cin, yourString);
Run Code Online (Sandbox Code Playgroud)
...当它到达换行符时将丢弃输入流.了解更多关于此功能在这里.
另一个直接丢弃流的选项是......
#include <limits>
// Possibly some other code here
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Run Code Online (Sandbox Code Playgroud)
祝好运!
小智 9
int i;
cout << "Please enter an integer value: ";
// cin >> i; leaves '\n' among possible other junk in the buffer.
// '\n' also happens to be the default delim character for getline() below.
cin >> i;
if (cin.fail())
{
cout << "\ncin failed - substituting: i=1;\n\n";
i = 1;
}
cin.clear(); cin.ignore(INT_MAX,'\n');
cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";
string myString;
cout << "What's your full name? (spaces inclded) \n";
getline (cin, myString);
cout << "\nHello '" << myString << "'.\n\n\n";
Run Code Online (Sandbox Code Playgroud)
小智 5
怎么样:
cin.ignore(cin.rdbuf()->in_avail());
Run Code Online (Sandbox Code Playgroud)
小智 5
另一种可能的(手动)解决方案是
cin.clear();
while (cin.get() != '\n')
{
continue;
}
Run Code Online (Sandbox Code Playgroud)
我不能将 fflush 或 cin.flush() 与 CLion 一起使用,所以这很方便。
归档时间: |
|
查看次数: |
276552 次 |
最近记录: |