您如何限制C ++中用户输入的最大字符数? [英] How do you limit the maximum amount of characters in user input in C++?
问题描述
我想要它,以便当用户输入超过5个字符时,会发生某些事情,而不仅仅是跳过其余字符。
I want it so that when the user inputs more than 5 characters, something will happen, instead of just skipping the rest.
在此代码中,如果您键入如果超过5个字符,则只会显示前5个字符。
我想在此处添加 if语句,如果用户输入的字符超过5个,它将显示错误或类似内容,而不仅仅是显示前5个字符。
In this code, if you type in more than 5 characters, it will only show the first 5 characters. I want to put an "if" statement here that if the user inputs more than 5 characters, it will show an error or something, and not just show the first 5 characters.
#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;
}
谢谢!
推荐答案
您可以先完整读取字符串,然后验证它:
You could read the string in its entirety first and then validate it:
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在评论中指出的那样,这部分实际上不是必需的。)
Incidentally, you should use std::endl
with your prompt and not just \n
; you want to make sure that the prompt is flushed to the screen before you start waiting for user input. ( As Loki Astari points out in the comments, this part's not actually necessary.)
这篇关于您如何限制C ++中用户输入的最大字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!