Need some help with this.

I am working on a program where i prompt the user for his/her name and i have to verify that the name only contains alphabetic characters.

here is my coding. It works to an extent i just can't get it to work the way it is supposed to.

#include <iostream>
#include <cstring>
using namespace std;

const int SIZE = 50;

int main()
{

char name[SIZE];

cout << "What's your first name?" << endl;
cin.getline(name, SIZE);

for (int x = 0; x < strlen(name); x++)
{
if (name[x] >= 65 && name[x] <= 90 || name[x] >=97 && name[x] <=122)
{
cout << "Valid name." << endl;
}
else
{
cout << "Your name cannot contain: " << name[x] << endl;
cout << "Invalid name." << endl;
}
}

when someone types in a name with only alphabetic characters it outputs valid name for how long the name is. For Ex: bob is three characters so it would output valid name three times. also when you put in a name with a number or character at the end it outputs valid name for the correct characters but also outputs the invalid character and invalid name which its supposed to do. the valid name should not be showing up though.



I would use another variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
bool isValidName = true;
for (int x = 0; x < strlen(name); x++)
{
    if (!isalpha(name[x])) // You can also use isalpha in <cctype>, by the way
    {
        isValidName = false;
        cout << "Your name cannot contain: " << /* etc. */;
        // ...
    }
}
if (isValidName)
    cout << "Valid name.";
// ... 
Topic archived. No new replies allowed.