我设置了一个 for 循环,根据用于此深度优先搜索算法的邻接列表的节点数,接收用户输入 X 次。
int nodeNum;
cout << "Number of nodes?: " << endl;
cin >> nodeNum;
cout << "Names: " << endl;
for (int i = 0; i < nodeNum; i++)
{
getline(cin, tempName);
v.push_back(tempName); //pushing the name of node into a vector
}
当我将其提交到我所在大学和 GCC 的在线编译器时,它会跳过最后的输入。示例 - 我输入数字 8,它只需要 7 个节点。我怎样才能解决这个问题?
最佳答案
声明cin >> nodeNum
读取整数,但在整数之后,但在换行符之前,立即保留文件指针。
因此循环的第一次迭代读取该换行符作为第一行。您可以通过以下方式看到此效果:
#include <iostream>
using namespace std;
int main(void) {
int nodeNum;
string tempName;
cout << "Number of nodes?\n";
cin >> nodeNum;
cout << "Names:\n";
for (int i = 0; i < nodeNum; i++)
{
getline(cin, tempName);
cout << "[" << tempName << "]\n";
}
return 0;
}
sample 运行:
Number of nodes?
2xx
Names:
[xx]
aaa
[aaa]
一种解决方法是放置:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
紧接在 cin >> nodeNum
之后- 这会清除当前行末尾的字符。您需要包括 <limits>
头文件来使用它。
将更改应用于上面的示例代码:
#include <iostream>
#include <limits>
using namespace std;
int main(void) {
int nodeNum;
string tempName;
cout << "Number of nodes?\n";
cin >> nodeNum;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Names:\n";
for (int i = 0; i < nodeNum; i++)
{
getline(cin, tempName);
cout << "[" << tempName << "]\n";
}
return 0;
}
显着改善情况:
Number of nodes?
2xx
Names:
aaa
[aaa]
bbb
[bbb]
关于c++ - 在 C++ 中使用 cin 时使用循环计数被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29600405/