我试图在我的do while循环中使用计数器,但是如果我这样做会在第一次迭代中切断我的getline的第一个字母
这是do while循环..
do
{
cout << "Enter the name of your class: " << endl;
cin.get();
getline(cin, classnames[i]);
cout << "Enter how many units was the class: " << endl;
cin >> classunits[i];
cout << "Enter the grade you completed the class with: " << endl;
cin >> classgrades[i];
classgrades[i] = toupper(classgrades[i]);
i++;
} while (again());
例如,如果我输入english
,'e'
将在第一次迭代中被切断,但任何下一次迭代english
都会显示正常。
只有在我添加i++
我已经尝试了cin.ignore()
,但我仍然无法破解它!
答案 0 :(得分:0)
正如其他人所提到的,cin.get()提取并返回您要丢弃的输入流中的第一个字符。
答案 1 :(得分:0)
删除cin.get();
。它会读取您输入的第一个字符,甚至不会将其存储在任何位置,因此您输入的第一个字符不会存储在字符串中。
答案 2 :(得分:0)
在开头删除cin.get()
并在结尾处添加cin.ignore()
:
do
{
cout << "Enter the name of your class: " << endl;
// cin.get(); // remove
getline(cin, classnames[i]);
cout << "Enter how many units was the class: " << endl;
cin >> classunits[i];
cout << "Enter the grade you completed the class with: " << endl;
cin >> classgrades[i];
classgrades[i] = toupper(classgrades[i]);
cin.ignore(); // add
i++;
} while (again());