c++ - 有先前输入时如何使用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;
}
我希望将“名称”数据输入到程序中。但是程序跳过了代码行或使用了剩余数据。
解决方案
你不需要cin.clear();
或cin.sync();
。cin.ignore();
在 getline 之前使用。
推荐阅读
- javascript - 如何使用带有 jquery 的复选框来获取打印值?
- node.js - 有没有办法可以在 node-postgresql 中重构我的 createTable
- ruby - 无法使用 HTTParty 获取对等证书
- mysql - mysql创建行到列
- spring-boot - 在 thymeleaf 中显示实体级错误消息
- python - 在 INSTEAD OF INSERT 期间获取触发器插入的行的 ID
- python - 如何在 Python 中运行协程?
- ios - 从另一个视图控制表格显示
- css - 字形CSS未加载
- c# - 如何将 typeof 类 T 转换为类 T 本身以执行方法
Method 接受 lambda 参数在哪里?