1

The following is the code. It contains a struct student with int rno and string name as members. I use a loop to read the members of all student variables. But the program terminates as soon as i enter any letter. Also, the string entered is not displayed.

#include <iostream>
#include <string>

using namespace std;
int main() {
    struct student {
        int rno;
        string name;
    };

    student s[4];

    int i;
    for( i = 0; i < 4; ++i) {
        cin >> s[i].rno;
        getline( cin, s[i].name );
    }

    string line = "";
    for( i = 0; i < 80; ++i) line += '-';

    cout << line << "ROLL\tNAME\n" << line << '\n';

    for( i = 0; i < 4; ++i) {
        cout << s[i].rno << '\t' << s[i].name << '\n';
    }
}

Thank you.

Max Payne
  • 2,423
  • 17
  • 32

2 Answers2

2

Your problem is using the >> stream operator and then using getline without flushing the stream of any unwanted new line characters.

Then when you read in the next struct you'll have the string you wanted to be the previous elements name and your stream will likely fail to read in an integer (unless the name started with a number).

So your read in loop should use cin.ignore(MAX_INT,'\n') or instead of MAX_INT some value longer than any line you would expect.

cin.ignore will ignore the next X characters or until it reaches the specified character (in this case MAX_INT character or until it reaches the newline character '\n').

Your read in for loop would then look like:

for (i = 0; i < 4; ++i){
    cin >> s[i].rno;
    cin.ignore(MAX_INT, '\n');
    getline(cin, s[i].name);
}
Timothy Murphy
  • 1,322
  • 8
  • 16
  • Thank you for the explanation! max_int should be greater than no of digits in rno right? ie it should be greater than no. of characters input earlier? – Max Payne Jan 08 '16 at 10:52
  • Yeah, I just use MAX_INT if it's defined on the system i'm using. I'm not sure if all systems have it defined. But you could also use the numeric_limits in the standard library if needed. – Timothy Murphy Jan 08 '16 at 10:53
0

try to add cin.ignore() after get an int type and before get char type

and for getting char array it's better to use gets()

#include <iostream>
#include <string>
using namespace std;

struct student {
    int rno;
    string name;
};

int main() {
    student s[4];
    int i;
    for( i = 0 ; i < 4 ; ++i) {
        cin >> s[i].rno;
        cin.ignore();
        gets(s[i].name);
    }
    string line = "";
    for( i = 0 ; i < 80 ; ++i) line += '-';
    cout << line << "ROLL\tNAME\n" << line << '\n';
    for( i = 0 ; i < 4 ; ++i)
        cout << s[i].rno << '\t' << s[i].name << '\n';
}

cin leaves the newline character in the stream. Adding cin.ignore() to the next line clears/ignores the newline from the stream.
This is used mainly with combinations of cin and getline.

see documentation and this question too

Community
  • 1
  • 1
Arash Hatami
  • 5,297
  • 5
  • 39
  • 59