Trying out *getline(cin, VarName)* Help.

I'm trying to enter a name the second time the loop goes but it skips the entering phase for the name each time. I cannot for the life of me figure out why.

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>
using namespace std;
int main ()
{
	char Letter;
	int Minutes;
	int Money;
	int LCV = 0;
	string Name[3];
		for (LCV = 0; LCV <= 2; LCV++)
		{
			cout<<"Enter name: ";
			getline(cin, Name[LCV]);
			cout<<"Enter Letter: ";
			cin>>Letter;
			cout<<"Enter Minutes: ";
			cin>>Minutes;
			cout<<Name[LCV]<<endl;
			cout<<Letter<<endl;
			cout<<Minutes<<endl;
		}
	return 0;
}
When you enter the minutes you type some digits and then press enter, which is converted to a newline character. The cin>>Minutes statement reads the digits but leaves the newline in the stream. Then the getline call reads the newline, thinking it's just a blank line. So you need to clear the newline character from the stream.

Note that cin>>Letter also leaves the newline in the stream, but when reading an integer, like cin>>Minutes, it first skips any whitespace before reading the digits, so it doesn't screw things up at that point.

Anyway, to clear the newline after the cin>>Minutes, you could use another getline call
1
2
string dummy;
getline(cin, dummy);

or you could use cin's ignore method
1
2
#include <limits> // add this to your includes
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

BTW, to use string you should include <string>.
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
#include <iostream>
#include <string>
#include <limits>
using namespace std;

int main ()
{
	string name[3];
	char letter;
	int minutes;

	for (int i = 0; i < 3; i++)
	{
		cout << "Enter name: ";
		getline(cin, name[i]);

		cout << "Enter letter: ";
		cin >> letter;
		// may as well clear out any excess characters that may have been typed
		cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

		cout << "Enter minutes: ";
		cin >> minutes;
		if (!cin) cin.clear(); // if the user entered an initial non-digit, the stream will "go bad", so clear the error flag
		cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

		cout << name[i] << '\n' << letter << '\n' << minutes << '\n';
	}

	return 0;
}

Topic archived. No new replies allowed.