compiler jumping

when i run this code.
output going bit crazy
output:
enter name: aa
eneter account :111
enetner name enter account
not letting me entrance a name and already that account jump
how should i avoid this?

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
33
34
35
#include<iostream>
#include<fstream>
using namespace std;
class Student {
	char name[20];
	int account;
public:
	void setName() {
		cout << "Enter name" << endl;
		cin.getline(name, 20);
		cout << "Enter account" << endl;
		cin >> account;
	}

};
void write_student();
int main() {
	for (int i = 0; i < 4; i++) {
		write_student();
}



	system("pause");
	return 0;
}
void write_student() {
	fstream file;
	file.open("student.txt", ios::out);
	Student obj;
	obj.setName();
	file.write((char*)&obj, sizeof(obj));
	file.close();

}
That's a very common problem when mixing getline() and formatted input using the >> operator.

There's an imbalance because the getline() will read until the end of the line, and discard the newline character '\n'. On the other hand, cin >> account; stops reading as soon as it encounters any trailing whitespace and leaves the newline character '\n' remaining in the input buffer. On the second iteration, the getline finds that unwanted newline and read an empty string.


Possible solutions:
1. use the ws manipulator to skip any trailing whitespace after the account number:
1
2
3
4
5
6
    void setName() {
        cout << "Enter name" << endl;
        cin.getline(name, 20);
        cout << "Enter account" << endl;
        cin >> account >> ws;
    }


2. Use ignore() to read and ignore any characters whether whitespace or not, after the account number. In the following example, it will ignore up to 1000 unwanted characters, or until the delimiter '\n' is found.
1
2
3
4
5
6
7
    void setName() {
        cout << "Enter name" << endl;
        cin.getline(name, 20);
        cout << "Enter account" << endl;
        cin >> account;
        cin.ignore(1000, '\n');
    }


http://www.cplusplus.com/reference/istream/ws/
http://www.cplusplus.com/reference/istream/istream/ignore/

The problem is that the operator>> leaves a new line in the stream. Read this:

http://en.cppreference.com/w/cpp/string/basic_string/getline

Specifically 'Notes' for how to solve this.


The data in the file may be overwritten. If you don't want it see the 'mode' part:

http://www.cplusplus.com/reference/fstream/fstream/open/
guys youre awsome thank you very much for your kind help .
Topic archived. No new replies allowed.