我玩了一个多星期都没有成功。现在它的运行方式将跳过while循环的第一次迭代的第一个字母。如果删除cin.ignore()
,则下面的代码不起作用。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
cout << fixed << setprecision(2);
float gpaTot = 0, gpa, clasNum;
int creds;
string clas, cont = "Yes", grade;
while (cont == "Yes"){
cin.ignore();
cout <<"Enter a course name: ";
getline(cin, clas);
cout << clas << endl << "Enter number of credits: ";
cin >> creds;
cout << creds << endl << "Enter your grade (A, B, C, D, F): ";
cin >> grade;
cout << grade << endl << "Continue ('Yes' or 'No')? ";
cin >> cont;
cout << cont << endl;
}
答案 0 :(得分:0)
将cin.ignore()
调用移至循环末尾。
while (cont == "Yes"){
cout <<"Enter a course name: ";
getline(cin, clas);
cout << clas << endl << "Enter number of credits: ";
cin >> creds;
cout << creds << endl << "Enter your grade (A, B, C, D, F): ";
cin >> grade;
cout << grade << endl << "Continue ('Yes' or 'No')? ";
cin >> cont;
cout << cont << endl;
cin.ignore();
}
这样,对getline
的第一次调用不会跳过字母。后续调用也可以正常进行,因为cin >> cont;
读取并丢弃了cin.ignore()
行中剩余的换行符。