0

I created a simple structure and function for entering all the data for it. The problem is that if you use cin inside a function for input, then a line break is thrown into the stream.

Strangeness lies in the fact that if I put the input ID at the beginning, cin throws '\n' into the stream, but if I first enter the name, and only then the salary and iD, then there is no problem with the new line and cin.

#include <iostream>

using namespace std;


struct Worker {

        string name;
        int salary;
        int id;
};

Worker newWorker;

int setWorker () {

    cout << "\nNAME: ";
        if (!(getline(cin, newWorker.name)) || newWorker.name.size() < 1)
            return 1;
    cout << "\nID: ";
        if (!(cin >> newWorker.id) || newWorker.id < 1)
            return 1;
        cout << "\nSALARY: ";
        if (!(cin >> newWorker.salary) || newWorker.salary < 1)
            return 1;
    return 0;
  }

int main()
{
    setWorker();
    return 0;
}

Output if NAME first

NAME: DEN

ID: 1

SALARY: 1

Process returned 0 (0x0) execution time : 3.764 s Press any key to continue.

Output if ID first

int setWorker () {

    cout << "\nID: ";
        if (!(cin >> newWorker.id) || newWorker.id < 1)
            return 1;
    cout << "\nNAME: ";
        if (!(getline(cin, newWorker.name)) || newWorker.name.size() < 1)
            return 1;
    cout << "\nSALARY: ";
        if (!(cin >> newWorker.salary) || newWorker.salary < 1)
            return 1;
    return 0;
}

ID: 5

NAME:

Process returned 0 (0x0) execution time : 2.067 s

MFisherKDX
  • 2,840
  • 3
  • 14
  • 25

0 Answers0