有前一个输入时如何使用getline? getline(cin, stringName) 由于先前的输入而无法正常工作

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

'getline(cin,string)' 当我的代码中没有以前的输入时,工作效率很高。

如果有先前的输入(数据类型 int),编译器将忽略输入字符串数据类型 'getline(cin, string)' 的代码,并继续执行程序的其余部分。

这只是家庭作业,我已经尝试过更改数据类型。我写了 cin.clear();和 cin.sync();在 getline 函数之前。

#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;
}

我希望将 'name' 数据输入到程序中。但是程序跳了一行代码或者利用了剩余的数据

您不需要 cin.clear();cin.sync();。 在 getline 之前使用 cin.ignore();