2013-04-21 512 views
2

我想要它,以便当用户输入超过5个字符时,会发生一些事情,而不是仅仅跳过其余部分。如何限制C++中用户输入的最大字符数?

在此代码中,如果您键入的字符数超过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; 
} 

谢谢!

回答

3

你可以先完整阅读的字符串,然后验证它:

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;您希望在开始等待用户输入之前确保将提示刷新到屏幕上。 (编辑:作为洛基阿斯塔在评论中指出,这部分实际上不是必要的)

+0

谢谢!你知道如何在它说错误之后将它循环回“cout”吗? – Leroterr1 2013-04-21 18:58:49

+0

'do {cin >> nationname; if(nationname.size()> maxchar)/ * output * /} while(nationname.size()> maxchar);' – Zaiborg 2013-04-21 19:03:01

+0

谢谢!詹姆斯德林和Zaiborg。 – Leroterr1 2013-04-21 19:21:07

0

**

#include <iostream> 
#include <iomanip> 
#include<string> 
#include <conio.h> 
int main() { 
    using namespace std; 
    const int maxchar = 6; 
    string nationname; 
    cout << "What is the name of your nation?" << endl; 
    getline(cin, nationname); 
    if (nationname.size() > maxchar) 
    { 
     cout << "The input is too Short." << endl; 
    } getch(); 
    return 0; 
} 

**

您可以使用此代码。这是完美的,没有任何错误。你也可以将其转换成最小字符,进行少许更改。