在CIN之后使用getline(CIN,s)我需要下面的程序来获取整个用户输入并将其放入字符串名称中:cout << "Enter the number: ";int number;cin >> number;cout << "Enter names: ";string names;getline(cin, names);带着cin >> number命令之前的命令。getline()命令(我猜这是问题所在),它不允许我输入名称。为什么?我听说了一些关于cin.clear()命令,但我不知道这是如何工作的,也不知道为什么这是必要的。
3 回答
互换的青春
TA贡献1797条经验 获得超6个赞
cout << "Enter the number: ";int number;if (cin >> number){
// throw away the rest of the line
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
cout << "Enter names: ";
string name;
// keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
while (getline(cin, name))
...use name...}else{
std::cerr << "ERROR reading number\n";
exit(EXIT_FAILURE);} char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}为什么不直接使用忽略呢?
ignore>> x
那么你什么时候才会使用“清除”和“忽略”呢?
std::cin.clear()std::cin.igore()
int x;while (std::cout << "Enter a number: " &&
!(std::cin >> x)){
if (std::cin.eof())
{
std::cerr << "ERROR unexpected EOF\n";
exit(EXIT_FAILURE);
}
std::cin.clear(); // clear bad/fail/eof flags
// have to ignore non-numeric character that caused cin >> x to
// fail or there's no chance of it working next time; for "cin" it's
// common to remove the entire suspect line and re-prompt the user for
// input.
std::cin.ignore(std::numeric_limits<std::streamsize>::max());}难道就不能用跳过或类似的简单点吗?
ignorestd::skipws
if (std::cin >> number >> std::skipws){
while (getline(std::cin, name))
...number1E6name
呼啦一阵风
TA贡献1802条经验 获得超6个赞
cout << "Enter the number: ";int number;cin >> number;cin.ignore(256, '\n'); // remaining input characters up to the next newline character // are ignoredcout << "Enter names: ";string names;getline(cin, names);
- 3 回答
- 0 关注
- 1023 浏览
添加回答
举报
0/150
提交
取消
