0

'getline(cin,string)' works efficiently when there is no previous input in my code.

When there is prior input (data type int) the compiler ignores the code to imput string data type 'getline(cin, string)' and proceeds with the rest of the program.

This is just a Homework assignment, I already tried to change the data type. I wrote cin.clear(); and cin.sync(); before the getline funtion.

#include <iostream>
#include <string>

using namespace std;
int main() {
     const int SECRET =11;

        double num1;
        double num2;
        int newNum;
        string name;

        cout <<"Please enter two whole numbers" <<endl;
        cin >>num1 >>num2; /*HERE I MADE THIS LINE A COMMENT AND THE          GETLINE FUNTION WORKED AS USUAL.*/


        cout <<"\nThe value of the first number is " <<num1 <<" and the value of the second number is " <<num2 <<endl;
        newNum =(num1*2) +num2;
        cout <<"The new number is: "<< newNum <<endl;
        newNum =newNum +SECRET;
        cout <<"The UPDATED new number is: " <<newNum <<endl;
        cin.clear();
        cin.sync();

    cout <<"Imput your name" <<endl;
    getline (cin,name);
    cout <<"Your name is " <<name <<endl;

    return 0;
}

I expected to input the 'name' data into the program. But the program jumped the line of code or utilized leftover data.

Santiago
  • 29
  • 1
  • 4
  • You are mixing getline and `>>` input methods. That is risky. – Yunnosch Sep 20 '19 at 15:24
  • 3
    Possible duplicate of [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Algirdas Preidžius Sep 20 '19 at 15:24

1 Answers1

0

You don't need cin.clear(); or cin.sync();. Use cin.ignore(); before getline.

Losak
  • 26
  • 4