【发布时间】:2016-02-23 20:55:57
【问题描述】:
我的程序应该创建一个简单的列表:name(string)、rating(int)、watched/unwatched(string)。
我知道使用std::cin>> 会在最后留下'\n',所以我必须使用cin.ignore(),但它似乎也以某种方式失败了。
void write()
{
int rating;
string name, watch, wprint;
cout << "Modifying" << endl;
f_list.open ("TextFile.txt", ios::app);
cout << "Name/Title?" << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, name);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Rating?" << endl;
if (!(cin >> rating));
{
cin.clear();
cout << "Error again" << endl;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Watched or unwatched?" << endl;
getline(cin, watch);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (watch == "w" || watch == "yes" || watch == "y")
{
watch = "W";
wprint = "Watched";
}
else
{
watch = "DW";
wprint = "Didn't watch";
}
cout << name << " (" << rating << "/10) (" << wprint << ") has been added to the list" << endl;
f_list << name << " " << rating << " " << watch << endl;
}
首先我的cin >> rating 始终为零,无论我做什么,它也会返回错误并进入无限循环。然后我以某种方式修复了它,但我不知道如何修复,现在我的 2 getline()s 需要输入两次!
有人能解释一下为什么这对我不起作用吗?这段代码的哪些部分是不必要的?
【问题讨论】:
-
std::getline不会将\n留在缓冲区中,格式化提取会!您正在清除输入。 -
...您害怕将您的问题标记为重复的问答并没有说在每次提取之间调用
std::istream::ignore。