storing string array

I need help with this stupid code.

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

void getnames(string names[], int numStd)
{
	
	for (int i = 0; i < numStd; i++)
	{
		cout << "Enter the name of the student #" << i + 1 << ": ";
		cin.ignore();
		getline(cin,names[i]);
	}
}


void getScores(string names[], int scores[NUM_STUDENTS][NUM_SCORES], int numStd, int numScores)
{
	for (int i = 0; i < numStd; i++)
	{
		cout << "Enter the grades of " << names[i] << ": " << endl;
		for (int j = 0; j < numScores; j++)
		{
			cout << "Grade #" << j + 1 << ": ";
			cin >> scores[i][j];
		}
	}
}



Enter the name of student #1: Angel Perez
Enter the name of student #2: Edwin la torre
Enter the grades of Angel Perez:
Grade #1: 56
Grade #2: 87
Enter the grades of dwin la torre:
Grade #1: 98
Grade #2: 78
Grades:
Angel Perez: 71
dwin la torre: 88
Press any key to continue . . .


notice how the second name isn't displaying correctly? i need that fix this NOW, I'm about to explode because I simply don't understand whats going on.

Last edited on
cin.ignore() removes one character. That's why "Edwin la torre" becomes "dwin la torre".
but i need cin.ignore() or i'll get something like:

Enter the name of student #1: Angel Perez
Enter the name of student #2: Enter the grades of Angel Perez:
Grade #1:

It happens every time i enter first and last names separated by a space. With the ignore, it doesn't happen, but it eats a letter -.-....any solutions?
Mixing >> and getline often lead to problems like that. The easiest way to handle it is probably to use std::ws before each call to std::getline.

1
2
3
cout << "Enter the name of the student #" << i + 1 << ": ";
cin.ignore();
getline(cin >> ws, names[i]);

http://en.cppreference.com/w/cpp/io/manip/ws

It is possible to make it work using cin.ignore() but it requires that you have good understanding of how these things work.
Last edited on
Topic archived. No new replies allowed.