I'm having a problem with our assignment this week.
What I have is a function that has the user enter data into several parallel arrays(name,age,gender,gpa). Since we don't know ahead of time how many entries
there will be, the assignment says to use:
"Press ctrl-z to quit", and then the function exits. this part works fine.
Now we have to ask the user which field he would like to sort on, and then use
a bubble sort to display the data sorted on the requested field.
The problem I am having is that after the data is entered(then a ctrl-z),
I display the menu asking which field to sort on.
The computer completely skips the cin command, I am pretty sure because
the ctrl-z is still in the buffer. If I drop the capacity(max size of the array)
down to 3 or 4, and then fill the array, the function exits without the
ctrl-z, and everything else works fine, including the sort.
cin.ignore() doesn't work either.
This is the function:
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 getData(string names[],int ages[], char genders[], double gpas[], int capacity,int &n)
{
string name;
cout << "enter the first name please" << endl;
while (cin>>name)
{
names[n]=name; //place value into array
cout << "enter " << name << "'s age :";
cin >> ages[n];
cout << "enter " << name << "'s gender (M/F) :";
cin >> genders[n];
cout << "enter " << name << "'s gpa :";
cin >> gpas[n];
n+=1; //increment number of values
if (n<capacity)
cout << "enter next name, ctrl-z to quit " << endl;
else
{
cout << "array is full, no more ages allowed"<< endl;
system("pause");
break;
}//else
}//while
}//getData
|
And this is the section of code that should get input from the keyboard
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 32
|
getData(names,ages,genders,gpas,SIZE,n);
cout << "The unsorted values are:\n";
showArray(names,ages,genders,gpas,n);
cout << endl;
while (true)
{
cout << endl << "How would you like the data sorted?" << endl;
cout << "1) By age" << endl;
cout << "2) By name" << endl;
cout << "3) By gender" << endl;
cout << "3) By gpa" << endl;
cin.ignore();
cin.get(sortType);
switch (sortType)
{
case '1' :
sortArray(ages,names,genders,gpas,n);
break;
case '2' :
sortArray(names,ages,genders,gpas,n);
break;
case '3' :
sortArray(genders,ages,names,gpas,n);
break;
case '4' :
sortArray(gpas,names,ages,genders,n);
break;
} //switch
showArray(names,ages,genders,gpas,n);
system("pause");
|
When stepping through, the cin (and I also tried cin >> sortType) gets skipped
and it drops out of the switch(I haven't bothered to put a default case
in there yet.
Any ideas?