While Statement Isn't Being Read Correctly

I'm trying to write a function that allows a user to enter a name. The name cant be over 10 characters and they need to confirm their username. I don't want the user to put anything other than y or n for their confirmation answer. For some reason the first time it tries to confirm your name, it asks you to re-enter your answer, regardless if it was Y or N. I'm new at this, so it could be a simple problem, but all help will be appreciated.
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
string nameDecision(string name)
{
	char decision;	
	std::string NameS;
	do 	
	{
		cout << "Please enter your name: " << endl << "Maximum of twelve characters" << endl;
		std::cin >> NameS; 

		while(NameS.length() >= 11)
		{
			cout << "Your name is too long. Please re-enter your name." << endl;
			std::cin >> NameS;
 		}
		
		cout << "Your name is ";
		std::cout << NameS; 
		cout << ", correct?" << endl << "Y/N" << endl;
		cin >>	decision;
		 
 while(decision!='n'||decision!='N'||decision!='Y'||decision!='y')
		{
			cout << "Please re-enter your answer using Y or N." << endl;
			cin >> decision;
		}
		
		name = NameS;
	}	while(decision=='n'||decision=='N');
	return name;
Last edited on
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
36
37
38
39
#include <iostream>
#include <string>

bool correct( const std::string prompt )
{
    std::cout << prompt << ". is this correct (y/n)? " ;
    char ch ;
    std::cin >> ch ;
    if( ch == 'y' || ch == 'Y' ) return true ;
    else if( ch == 'n' || ch == 'N' ) return false ;

    std::cout << "please enter either y or n\n" ;
    return correct(prompt) ;
}

std::string get_name( std::size_t max_len = 10 )
{
    std::cout << "Please enter your name (maximum of "
              << max_len << " characters): " ;

    std::string name ;
    std::cin >> name ;

    if( name.size() <= max_len )
    {
        if( correct( "your name is '" + name + "'" ) ) return name ;
    }

    else std::cout << "the name is too long. " ;

    std::cout << "please re-enter your name\n" ;
    return get_name(max_len) ;
}

int main()
{
    const std::string name = get_name() ;
    std::cout << "name: " << name << '\n' ;
}
The issue is with your condition here for the loop:
1
2
3
4
5
while (decision != 'n' || decision != 'N' || decision != 'Y' || decision != 'y')
{
	cout << "Please re-enter your answer using Y or N." << endl;
	cin >> decision;
}


By using "||" instead of "&&", you're saying that only ONE of those conditions have to be true for the whole thing to be true. So, if you input "n", n is not "N" or "Y" or "y", therefore, the condition will become true. You want to replace "||" with "&&"
Topic archived. No new replies allowed.