persons name while loop

the name can consist of letters spces a single quotation mark and a single hyphen. if there is a illegal character the program will ask to re enter name.

only new to coding so pleas bare with me. not really sure how to go about using the while loop and have been trying a few things and this is the best I came up with,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
   using namespace std;
#include <conio.h>
#include <iostream>
#include <string>

int main(){

string name;
bool valid = true;

cout<<"Please enter your name: ";
getline(cin, name, '/n')

if (!isalpha(name))
   valid=false;
else if (name==' ')
   valid==true
else if (name=='-')
    valid=true;

else if (name==' '*2||name=='-'*2)
    valid=false;


if (valid)
cout<<name<<" is a valid name";

else cout<<"sorry that is a incorrect name";

//cout<<"Please enter your name: ";
//cin>>name;

getch();
return 0;
}
You can only use isalpha one character at a time. Since it seems you're trying to figure out loops, try using it in a loop over the whole line, for example I've used a for loop here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void func(const string &name)
{
	bool valid = true;
	for (string::const_iterator it = name.begin(); it != name.end() && valid; ++it)
	{
	    if (!isalpha(*it) && !isspace(*it))
	    {
	        valid = false;
	    }
	}	
	
	if (valid)
	{
		cout << name << " is a valid name" << endl;
	}
	else
	{
		cout << name << " is not a valid name" << endl;
	}
}
ok have been at it all day and ive changed it to a do while but its still not working, and when I input a wrong name it repeatedly couts" is not a valid name" "please enter your name" as its suppose to but not so many times.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 using namespace std;
#include <conio.h>
#include <iostream>
//#include <string>

int main(){
    char name;
bool valid;

do{
     valid = true;
    cout<<"Please enter your name: ";
cin>>name;
if (!isalpha(name))
   valid=false;
 if (name==' ')
   valid=true;
 if (name=='-')
    valid=true;
if (name==' '*2)
    valid=false;
if (name=='a'*2)
    valid=false;

    if (valid)
cout<<name<<" is a valid name";

if(!valid) cout<<"sorry that is a incorrect name:\n";

}
while (!valid);
//getch();
return 0;
}
Well those comparisons look mighty dodgy, but I think your problem is with how you're using cin.

As an experiment, try using name = getchar() instead of cin>>name and see what happens.
Topic archived. No new replies allowed.