How do you limit the maximum amount of characters in user input in C++?

不羁的心 提交于 2019-12-24 02:18:57

问题


I want it so that when the user inputs more than 5 characters, something will happen, instead of just skipping the rest.

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;
}

Thanks!


回答1:


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;
    }

    // ...
}

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. (Edit: As Loki Astari points out in the comments, this part's not actually necessary.)




回答2:


**

#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; 
}

**

you can use this code. This is working perfectly without any errors. Also you can convert this into minimum character enter making few changes.



来源:https://stackoverflow.com/questions/16134822/how-do-you-limit-the-maximum-amount-of-characters-in-user-input-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!