在第一次输入之后忽略第一个字符的C++程序

在第一次输入之后忽略第一个字符的C++程序,c++,input,cin,C++,Input,Cin,下面是我请求输入的主类中的代码 Class in(nameOfClass, numOfStudents); for (int i = 0; i < numOfStudents; i++) { cout << "\nEnter the name of student " << i + 1 << ": "; string studentName = ""; cin.ignore(); getline(cin, studentN

下面是我请求输入的主类中的代码

Class in(nameOfClass, numOfStudents);
for (int i = 0; i < numOfStudents; i++)
{
    cout << "\nEnter the name of student " << i + 1 << ": ";
    string studentName = "";
    cin.ignore();
    getline(cin, studentName);
    cout << "\n ~ Enter the grades for " << studentName << endl;
    cout << " ~ (Use this format: 3 - 100 100 100)" << endl;
    cout << " ~ ";
    string gradeLine = "";
    getline(cin, gradeLine);
    Student stu = Student(studentName, gradeLine); in .addStudent(i, stu);
    cout << endl;
}
对于循环的第一次运行,studentName将读取自我使用getlinecin、studentName;以来的所有字符,包括空格;。如果我输入Andrew,则studentName将在Andrew中读取

但是,对于所有进一步运行的循环,如果我输入Andrew作为学生的名字,程序将ndrew存储到studentName变量中。我尝试在循环中的不同位置使用cin.ignore、cin.clear和cin.sync,但它停止了输入,我需要输入一个“\n”,以便它继续并询问下一个学生的信息


循环完成后如何清除缓冲区,以便下次运行循环时读取所有字符,但循环不会暂停并等待用户输入“\n”?

到目前为止,我在输入流代码中看到的唯一错误是cin.ignore行。其他的一切看起来都应该是可行的。如果我省略了cin.ignore,那么编译器将跳过读取学生姓名的部分。它只是打印出来,输入学生1的名字:~输入以前输入的分数,其中留下了剩余的空白。将cin.ignore替换为cin>>ws。是,cin>>ws;工作。谢谢,太好了!顺便说一句,std::cin.ignore只忽略单个字符,而std::cin>>std::ws清除空白,直到找到非空白字符为止。std::cin.clear不是一个输入函数,它只是在默认情况下清除流上的所有错误标志。最后,std::cin.sync相当于刷新输出流缓冲区,仅用于输入流。它的行为是高度实现定义的,因此没有理由使用它。