alphabetical characters.

hi, i have updated some code, and i need help compressing the second part of the code, the first that i have checks each character and outputs valid name for each alphabetical character and invalid name for each nonalphabetical character. but what i want is i want to check each character and if they are all valid name characters then output Valid name, otherwise Invalid name, and output the characters that should not be there, Example: Starcraft is a Valid name, 5t4rcr4ft is not a valid name, then output 5, 4, 4 are not valid name characters.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char first_name[100];

    cout << "What's your first name?" << endl;
    cin >> first_name;

    for(int i = 0; i < first_name[i] != '\0'; i++)
    {
        if (first_name[i] >= 'A' && first_name[i] <= 'Z' || first_name[i] >= 'a' && first_name[i] <= 'z')
        {
            cout << "Valid name." << endl;
        }
        else
        {
            cout << "Invalid name." << endl;
        }
    }

}
Last edited on
The compiler error can be fixed by changing the i < first_name; on line 13 to first_name[i] != '\0';.
(You're getting the error because you're trying to compare the value of your int i variable with your char first_name[100] string.)

Two other things:
1) Don't use magic numbers like the 65, 90, 97, and 122 you have there.
You can actually just use the characters themselves:
if ( (first_name[i] >= 'A' && first_name[i] <= 'Z') || /* ... */ )

2) Your program will print "Valid name." for each valid character in the name and "Invalid name." for each invalid character.
So if I entered "Ju#ly", the program output would be
Valid name.
Valid name.
Invalid name.
Valid name.
Valid name.
.
To fix that, consider making a bool variable (initially set to true) representing whether or not the name is valid, and if you find an invalid character, set it to false.
Then, after the for loop, print "Valid name." or "Invalid name." based on the value of that variable.
ok thank you ill do some work right now, ill replay back if i run into a problem again. thanks
Topic archived. No new replies allowed.