0

I tried to input string inside the function, getline(cin, worker->Name) works for the first time input but for the next input it skips or got ignored. it works for the integer but it doesn't work for the string, what should I do?

Code:

#include <iostream>
using namespace std;

struct Worker {
    string Name;
    int Salary;
    int Status;
    int Child;
};

void InputWorkerData(Worker *worker) {
    cout << "Nama: ";
    getline(cin, Worker->Name);
    cout << "Gaji per bulan: ";
    cin >> worker->Salary;
    cout << "status (menikah = 1, single = 0): ";
    cin >> worker->Status;
    if(worker->Status == 1) {
        cout << "jumlah anak: ";
        cin >> worker->Child;
    } else {
        worker->Child = 0;
    }
    cout << endl;
}

int main() {
    Worker worker1, worker2, worker3;
    InputWorkerData(&worker1);
    InputWorkerData(&worker2);
    InputWorkerData(&worker3);

    return 0;
}

Output:

Nama: michael jordan
Gaji per bulan: 7000
status (menikah = 1, single = 0): 1
jumlah anak: 3

Nama: Gaji per bulan: 5000
status (menikah = 1, single = 0): 0

Nama: Gaji per bulan: 9000
status (menikah = 1, single = 0): 1
jumlah anak: 2

  • 2
    Does this answer your question? [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – rawrex Jun 19 '21 at 08:10
  • @rawrex I put `cin.ignore()` at the end of the InputWorkerData() function and it works! is this the right thing to do? – Wilasta Kurniawan Jun 19 '21 at 10:36

2 Answers2

0

Mixing line-oriented and item-oriented input can (and often will) lead to problems like this.

This seems to fit the typical case: after reading an item (in this case a number) using >>, there's a new-line character still sitting in the input buffer. When you call getline, it sees that new-line character as the end of an otherwise empty line.

There are a few ways to avoid this problem. One common, well-known one is to use getline to read input a line at a time throughout, then use (for one possibility) a lexical_cast to convert the data from a string to the type you actually wanted to read.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
-1

use fflush(stdin) after each input i.e after cout and before getline() .It will solve your problem.you have to flushout the buffer first.

pushplata
  • 1
  • 1