首页 > 解决方案 > 有先前输入时如何使用getline?由于先前的输入,getline(cin, stringName) 无法正常工作

问题描述

当我的代码中没有以前的输入时,'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;
}

我希望将“名称”数据输入到程序中。但是程序跳过了代码行或使用了剩余数据。

标签: c++inputgetline

解决方案


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


推荐阅读