cin.getline skipped

after i insert number'1' in menu
c++ will skip "enter name"
what is the problem?

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
  #include <iostream>
using namespace std;
int main()
{
	char name[200][20] = {{"Jason Chong"},{"Patrick Ng"}};
	char type;
	int id[200], menu;


	cout<<"MENU LIST\n";
	cout<<"------\n";
	cout<<"1) Add Student and Marks\n";
	cout<<endl;

	cout<<"Menu :";
	cin>>menu;

	if(menu == 1)
	{
		for (int a=2; a<=199; a++)
		{
		cout<<"Enter Name :";
		cin.getline(name[a],20);
		cout<<"Enter ID :\n";
		cin>>id[a];
		}
	}
	system("pause");
	return 0;
}
Last edited on
use cin.clear(); and cin.ignore(); after cin >> menu
You need clear() only after an error (to reset the flags). It isn't necessary here. (except if the user entered an invalid number, but that requires additional code to handle properly).

The purpose of ignore() in this context is to remove the newline character '\n' which remains in the buffer after the cin >> which otherwise is picked up by the next getline() and interpreted as an empty line.
after i use cin.clear(); and cin.ignore(); after cin>>menu;
the "enter name" will show up only 1 time
if i wan to enter 1 more time,the problem will remaining
how to solve it?
You don't need cin.clear() here?

For your second question, if you want to repeat the entire process, you need some sort of loop. Normally a while loop would be useful. But you need to decide how to exit from the loop after completing all of the input.
so what should i correct in my code?
i just a new beginner to c++ so cant get you,sry.
Well, I wouldn't call it a correction, that implies there is an error. Rather, it is a change to the design. In terms of what code you should write, first of all, you need to be clear about what it is that you are aiming to achieve. Although I could attempt to guess that, you really need to specify in words what you want to happen.

What I'm saying is, you haven't supplied enough information about the task so far. For example, I see two arrays, name and id. Each array has a size of 200 elements. But how do you intend to use these arrays? Will there be exactly 200 students? Or some variable number. How do you want the input to be entered at the keyboard? Once you have decided how the program is to behave, then it is possible to write code to implement that behaviour.

yes,those codes just one part of the all .
i have finished other parts and left this part only
i am no going to use all of the elements
just assume the maximum size of elements is 200 .

the output should let the user to enter the student name and id if user choose menu 1.
after enter name and id,user will be asked want to continue or not
if they wan,then continue,if don't, then break,
those code i haven write in but i think i can finish this part first

example of output:

Enter Name:
Enter Id:
(if user want continue,will ask again)
Enter Name:
Enter id:



Topic archived. No new replies allowed.