c++ - 刚开始编写 C++
问题描述
我的代码中似乎有什么问题?
当我Enter输入年龄后点击时,提示已经结束,无需询问我的地址。我知道我可以使用getline()
年龄,但如果用户输入非整数答案怎么办?
抱歉,我昨天才开始编码,我想学习基础知识。
#include <iostream>
using namespace std;
int main()
{
int age;
string name, address;
cout << "Please enter the name of the user:" << endl;
getline(cin, name);
cout << "Please enter age of the user:" << endl;
cin >> age;
cout << "Please enter the address of the user:" << endl;
getline(cin, address);
cout << "Your name is " << name << " and you are " << age
<< " years old " << " who lives in " << address << endl;
cout << "Thank you for using my program!";
return 0;
}
解决方案
只需在 'cin>>age' 之后添加 'cin.ignore()',如下所示:
cout << "Please enter age of the user:" << endl;
cin >> age;
cin.ignore();
cout << "Please enter the address of the user:" << endl;
getline(cin, address);
当 getline() 读取输入时,输入流中会留下一个换行符,因此它不会读取程序中的字符串(地址)。
如果用户在 age 中输入 'float' 或 'double' 等而不是 'int' ,那么它将简单地从中提取整数,例如:如果用户输入 39.29 或 39.00005 或 39.00 或然后 age=39
推荐阅读
- python - 根据给定条件过滤数据框并添加新列
- typescript - 提取类型键的更易读的方法,其中所述键的值的类型符合接口?
- python - PyTorch 中层的类型及其激活函数有什么区别?
- python - 读取文件名末尾带有动态日期时间值的 xlsx 文件
- html - 根据弹性项目的数量确定容器的宽度
- javascript - Httpclient 返回未定义的响应
- gnuplot - 如何修复'GNUPlot不绘制二维轮廓数据的第一个点,通过绘制到表格生成
- javascript - 如何使用正则表达式仅获取字符串的特定部分?
- angular7 - 在 onsubmit 中收到 http 错误后重新验证 Angular 控件
- java - 使用 ProcessBuilder 在 Windows 上启动 java Minecraft 服务器