For循环内特定行的意外迭代
Unintended Iteration of a specific line inside a For Loop
不要担心代码的用途。但我会把它贴在下面供参考:
#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);
没有道理。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- For循环内特定行的意外迭代
- 意外结果迭代提升::p ython vector_indexing_suite
- 使用具有嵌套向量的迭代器的意外行为
- find_if() 在 const 函数中返回意外的迭代器类型
- 为什么多输入迭代器会导致意外结果
- 使用boost mpl插入器迭代器时出现意外结果