Invisible Hippo
Invisible Hippo

Reputation: 124

How to prevent integers being assigned to char strings?

I am very new at programming in c++, and I have come across this problem I can't solve. I am trying to create an error message whenever a user inputs integers instead of characters. The problem is, the integers are being accepted and assigned to the char strings for some reason.. I thought the point of defining the strings as int or char etc. was to let the compiler know what values are to be accepted. Could anyone let me know what i'm doing wrong?

int x, input = false;
char check[SIZE], str[SIZE];

cout << "Enter one word: ";
cin >> str;

while (!cin)
{
    cout << "\nERROR: You must enter only one word with characters. \n\nRe-enter: ";
    cin.clear();
    cin.ignore(256, '\n');
    cin >> str;
}

Upvotes: 0

Views: 402

Answers (2)

bpgeck
bpgeck

Reputation: 1624

A char is just a 1-byte interpretation of an integer according to an ascii value (i.e. the integer 68 is the ascii value for the character 'D'). Other ascii values can be found here.

For your code, you will likely need to create a function that loops through the inputted string and checks to see if any of the characters are not letters.

For example:

for (int i = 0; i <  strlen(str); i++)
{
    if ((int)str[i] < 65 || ((int)str[i] > 90 && (int)str[i] < 97) ||  (int)str[i] > 122)
    {
        // handle error
    }
}

Upvotes: 0

James Adkison
James Adkison

Reputation: 9602

First, use std::string instead of char[].

Second, "2" is a perfectly valid string.

Third, you can use find_first_of or similar to check if the string contains any values that are undesirable.

std::string::size_t result = str.find_first_of("0123456789");
if (result != std::string::npos)
{
    // Found an undesirable character
}

Upvotes: 5

Related Questions