Problems with "getline" function

I'm taking my first C++ class, and so far the instructor has only taught us to use the "cin <<" method of getting input from the user.

We have our first assignment using strings, and he recommended using the ignore() function to deal with cin and newline characters, but didn't explain very well how that worked, and it's not in our textbook. I started googling to try and find out how to use it and everything seemed to be telling me to use the getline function instead as it's much preferable for getting input.

I decided to go ahead and swap out my uses of cin with getline, but now my program doesn't work. Specifically, the compiler I'm using, Dev-C++, gives me the error "no matching function for call to 'getline(std::istream&,int&)' for the lines where I used it.

Not sure what I'm doing wrong as I've double checked with a few websites talking about getline and my syntax seems correct. I've included #<string>, #<sstream>, and #<iostream> at the top.

Here's the function where I was trying to use it. "Employee" is a struct I defined earlier in the code. If you need I can paste the whole program, it's not very long.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 Employee getEmployeeInfo()
 {
    Employee temp;       //Temporary Employee struct.
    
    // GET EMPLOYEE ID
    cout << "Employee ID: ";
    getline(cin, temp.empID);
    //VALIDATE EMPLOYEE ID INPUT
    while (temp.empID < 0)
       {
          cout << "Employee ID must be a number greater than 0. \n";
          cout << "Please enter a valid employee ID: ";
          getline(cin, temp.empID);
       }
       
    return temp;
 }


Thank you!
A friend helped me figure out what was wrong. getline() always stores input as a string, so the error was because I was trying to store a string value in an int variable. I used a string to temporarily hold the info and then pass it to temp.empID and now it works fine.

Here's the new code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Employee getEmployeeInfo()
 {
    Employee temp;  //Temporary Employee struct.
    string   input;      //Holds getline() data so it can be converted to a number
    
    // GET EMPLOYEE ID
    while (true)
    {
          cout << "Employee ID: ";
          getline(cin, input);  
        
          //CONVERT "INPUT" STRING TO NUMBER, STORE IN TEMP.EMPID, AND VALIDATE
          stringstream myStream(input);
          if (myStream >> temp.empID && temp.empID > 0)
             break;
          cout << "Employee ID must be a number greater than zero." << endl;
    }
       
    return temp;
 }
Topic archived. No new replies allowed.