Santiagopph48
Santiagopph48

Reputation: 171

How to use getline when there is a previous input? getline(cin, stringName) not working because of previous imput

'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.

Upvotes: 0

Views: 1283

Answers (1)

Losak
Losak

Reputation: 26

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

Upvotes: 0

Related Questions