在 C++ 中使用 cin 时使用循环计数被忽略
Use for loop count being ignored when using cin in C++
我设置了一个 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;
}
样本 运行:
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]
我设置了一个 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;
}
样本 运行:
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]