我希望当用户输入超过 5 个字符时,会发生一些事情,而不是跳过其余的。
在此代码中,如果输入超过 5 个字符,则仅显示前 5 个字符。 我想在这里放一个“if”语句,如果用户输入超过5个字符,它会显示错误或其他内容,而不仅仅是显示前5个字符。
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
string nationname;
int maxchar = 5;
cout << "What is the name of your nation?\n";
cin >> setw(maxchar) >> nationname;
cout << "The name of your nation is " << nationname;
cin.ignore();
return 0;
}
谢谢!
最佳答案
您可以先读取整个字符串,然后验证它:
int main()
{
using namespace std;
const int maxchar = 5;
string nationname;
cout << "What is the name of your nation?" << endl;
cin >> nationname;
if (nationname.size() > maxchar)
{
err << "The input is too long." << endl;
return 1;
}
// ...
}
顺便说一句,您应该在提示符中使用 std::endl
而不仅仅是 \n
;您需要确保在开始等待用户输入之前提示已刷新到屏幕上。 (编辑:正如 Loki Astari 在评论中指出的那样,这部分实际上并不是必要的。)
关于c++ - 如何限制 C++ 中用户输入的最大字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134822/