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

13,046

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.)

Share:
13,046
Leroterr1
Author by

Leroterr1

Updated on June 15, 2022

Comments

  • Leroterr1
    Leroterr1 almost 2 years

    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!