For循环内特定行的意外迭代

Unintended Iteration of a specific line inside a For Loop

本文关键字:意外 迭代 循环 For      更新时间:2023-10-16

不要担心代码的用途。但我会把它贴在下面供参考:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    int numberOfStudents;
    cout << "Please enter the number of students in the class:n ";
    cin >> numberOfStudents;
    string temporaryname,
           realname;
    for (int count = 0; count < numberOfStudents; count++)
    {
        cout << "Please enter the name of the student";
        getline(cin, temporaryname);
        if (temporaryname == temporaryname);
        else if (temporaryname < realname)
        {
            realname = temporaryname;
        }
    }
    cin.get();
    cin.get();
    return 0;
}

现在输出显示:

Please enter the number of students in the class:
 5
Please enter the name of the student
Please enter the name of the student

看到重复的"请输入学生姓名"了吗?它为什么这么做?我一点也不知道为什么它在重复同样的台词。还要注意的是,我是一个初学者C++程序员。请保持简单的解释。

在该语句之后

cin >> numberOfStudents;

换行符仍在输入缓冲器中。

下一个读取功能

getline(cin, temporaryname);

读取缓冲区,直到它遇到这个换行符。

您应该在循环之前使用成员函数ignore,以便在使用getline之前忽略缓冲区中的所有字符。例如

#include <limits>
//...
std::cin.ignore( std::numeric_limits<std::streamsize>::max() );

你的程序似乎包含一个拼写错误,因为这个语句

    if (temporaryname == temporaryname);

没有道理。