its a cin.ignore problem, please help

the cin.ignore(); is making the getline(); command loose one character in the name at the first round of the do loop, how do I fix this problem?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include <iostream>

using namespace std;

int main(){
	string a;
	char b;
	do{
	cout << " whats your name? ";
	getline(cin, a);
	getline(cin, a);
	cout << " hellow " << a <<endl;
	cout << " Again? <y/n> :";
	cin >> b;
	} while(b != 'n');
	system("pause");
}
Last edited on
Because you told to ignore one character. And it does exactly that.

Why everyone insist on using ignore, when usually proper approach for using getline after stream extraction is to discard whitespace characters only?

Remove ignore and use std::getline(std::cin >> std::ws, a);
thank you, I'm not sure if I correctly followed your instructions but now on the first round of the loop the howl name is lost

here is what I did
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main(){
	string a;
	char b;
	do{
	cout << " whats your name? ";
	getline(cin, a);
	getline(cin, a);
	cout << " hellow " << a <<endl;
	cout << " Again? <y/n> :";
	cin >> b;
	} while(b != 'n');
	system("pause");
}
Why you are using two getlines here? And where is the whitespace consumer std::ws?
so do you mean like this?

1
2
3
4
5

	cout << " whats your name? ";
	getline(cin >> ws, a);
	getline(cin, a);
	cout << " hellow " << a <<endl;
Last edited on
Drop second getline.
Thankyou so much, it worked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main(){
	string a;
	char b;
	do{
	cout << " whats your name? ";
	getline(cin >> ws, a);
	cout << " hellow " << a <<endl;
	cout << " Again? <y/n> :";
	cin >> b;
	} while(b != 'n');
	system("pause");
}
 


Topic archived. No new replies allowed.