Question

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!

Was it helpful?

Solution

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

OTHER TIPS

**

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top