Hello all, I am having a mental blank on checking user input (that is string) to check if it contains an integer value. as in:

for(i=0;i < nNames; i++){
		cout<<"\nEnter a last name: ";
		getline(cin,name[i]);

I have checked the C++ string class for string.length() and others, I am just not getting a idea of checking if it is a number/integer to cout a "that is not a alpha character."
Basically if(name != a string) or if(name == an int) type idea. - Could someone shed some light or some idea to point me in the right direction please? Thanks to all for any ideas : )

Google cctype library. Here is an example :

string n = "1232"
bool isNumber = std::count_if( n.begin() , n.end() , isdigit) == n.size(); // check if all element isDigit

The few function you would want to take a look at are isdigit() and isalpha() .

Does the string need to represent a valid value for a specific integer type? Or are you just looking for digit characters and possibly a sign?

@ Nature. Yes, I am just looking to see if the input is a integer. I want to "except" a-z and cout a message if the user enters a numeric value. So, if they were to enter "4567" or "1" for a last name, cout something like "Error: can not except numeric value for a name. ". (I guess signs would be a good idea as well, but optional at this point.) I hope I made myself understandable.

What I meant was, will you accept something like "999999999999999999999999999999999999999999999999999999999999999999999", which clearly won't fit in an integer variable? I ask because it's a trivial matter to check for digits only, as firstPerson has shown, but it's not as simple if you need to keep track of the numeric value and check for potential integer overflow.

No I do not want to except "99999..." or any numeric number, whether it's "9" or what you were asking. I understand that a numeric values can be considered string i.e. social security numbers, but here I am "wanting" not except any size of numeric value. Only alpha chars should be except-able.

Loop through the string however you want and call isalpha from <cctype>:

string s;

if (getline(cin, s)) {
    for (int i = 0; i < s.size(); i++) {
        if (!isalpha(s[i]))
            cout << "Not a number\n";
    }
}

Loop through the string however you want and call isalpha from <cctype>:

string s;

if (getline(cin, s)) {
    for (int i = 0; i < s.size(); i++) {
        if (!isalpha(s[i]))
            cout << "Not a number\n";
    }
}

Nice. that's what I was looking for. I just do not have a lot of experience with the isalpha(), isdigit() yet. Thank you for shedding some light. I see what is happening there, just could not visualize it before. Again, thanks mate!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.