I'm having trouble with string input in a loop

May 23, 2013 at 11:58pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string name;
	string city;
	char redo = 'y';

	while (redo == 'y')
	{
		cout << "enter name";
		getline(cin, name);
		cout << "enter city";
		getline(cin, city);

		cout << "Redo?";
		cin >> redo;

	}
	system("pause");
}


I'm writing a console application for a C++ course and it requires us to use a loop to have the user input a name, city, and 5 scores. This is the section of code I'm having problems with. I've narrowed it down by putting it in it's own application and testing it there. What happens when I run this code is that on the first iteration of the while loop it outputs:


enter name: i
enter city: i
redo? y
enter name: enter city:


The i in italic represents user input. It will change the string city if I input something after the redo line, but it just clears the string name. Any help?
May 24, 2013 at 12:26am
May 24, 2013 at 1:48am
Nothing in that thread helped me to solve my problem or even better understand it. It actually made me more confused because from what I understood of the original post was that they were having pretty much the same problem I am, but the answers they received solved their problem but didn't work for mine. I've read everything I could find about the getline(); function, as well as the cin.ignore();.
May 24, 2013 at 2:42am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string name;
	string city;
	char redo = 'y';

	while( redo == 'y' || redo == 'Y' )
	{
		cout << "enter name: ";
		getline(cin, name);
		cout << "enter city: ";
		getline(cin, city);
		std::cout << "name: '" << name << "'\ncity: '" << city << "'\n" ;

		cout << "Redo?";
		cin >> redo;
                std::cin.ignore( 100, '\n' ) ; // **** added *****
	}
}

See: http://www.cplusplus.com/forum/general/69685/#msg372532
May 24, 2013 at 2:58am
Well technically the stream size max is 2147483647 ( for some reason has a minimum of -2147483648 not sure why... how can you stream negative characters?) so might be a little more accurate to do std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' );
in case the user inputs more than 100 characters.
EDIT: it says that streamsize is a signed value so not sure why the min would be a negative value? meh oh well..
Last edited on May 24, 2013 at 3:00am
May 24, 2013 at 7:25pm
JLBorges, thank you. This solved my problem and helped me to understand what was going wrong.
Topic archived. No new replies allowed.