changing a name

1
2
3
4
5
6
case 1:
	char n1[20];
	cout << "Choose name: ";
	cin.getline(n1, 20);
	ref.setName(n1, 20);
	break;


i have this part of code i am having trouble with
the point is when the user inputs the number 1
it should ask him to enter another name
but as soon as i hit 1, it asks then skips to the other instructions and the name is changed to nothing
it is like its taking the enter and changing the name to that

any help of how to fix this?

PS: i cant use string, i have to use char array,
Bump
use if else, not switch
Whats the difference?
could you please post your full code?
it is long i cant
but i am sure that this is where something is wrong
Last edited on
I really need an answer regarding this matter, i dont have much time
closed account (zb0S216C)
It's because there's an un-extracted '\n' at the end of the input buffer. So when you call std::istream::getline( ), std::istream::getline( ) sees it and thinks it's done extracting. What you have to do is remove the contents of the buffer. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void clear_input_buf( )
{
    std::cin.ignore( std::numeric_limits< std::streamsize >::max( ), '\n' );
    return;
}

/* ... */

case 1:
        clear_input_buf( );
	char n1[20];
	cout << "Choose name: ";
	cin.getline(n1, 20);
	ref.setName(n1, 20);
	break;


Wazzak
Last edited on
Thank u for info framework
I used the same logic,
I used cin.ingore(); to clear the buffer
Topic archived. No new replies allowed.