its a cin.ignore problem, please help

Jul 1, 2015 at 5:37pm
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 Jul 1, 2015 at 7:04pm
Jul 1, 2015 at 5:45pm
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);
Jul 1, 2015 at 7:14pm
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");
}
Jul 1, 2015 at 7:24pm
Why you are using two getlines here? And where is the whitespace consumer std::ws?
Jul 1, 2015 at 9:02pm
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 Jul 1, 2015 at 9:03pm
Jul 1, 2015 at 9:05pm
Drop second getline.
Jul 1, 2015 at 9:21pm
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.