如何在c++中正确评估用户输入
How to correctly evaluate user input in C++?
在我的cpp文件中,我包括以下内容:
#include <cstdlib>
#include <iostream>
#include <string>
#include <math.h>
提示用户输入
double weight;
cout << "What is your weight? n";
cin >> weight;
string celestial;
cout << "Select a celestial body: n";
getline(cin, celestial);
然后我有以下语句:
if (celestial == "Mercury")
{
g_ratio = g_mercury / g_earth;
wt_on_celestial = g_ratio * weight;
cout << "Your weight on Mercury would be " << wt_on_celestial << " kilograms.";
}
else if (celestial == "Venus")
{
g_ratio = g_venus / g_earth;
wt_on_celestial = g_ratio * weight;
cout << "Your weight on Venus would be " << wt_on_celestial << " kilograms.";
}
else if (celestial == "The moon")
{
g_ratio = g_moon / g_earth;
wt_on_celestial = g_ratio * weight;
cout << "Your weight on the moon would be " << wt_on_celestial << "kilograms.";
}
当我运行代码时,我得到以下内容:
read from master failed
: Input/output error
我在获得输入方面做错了什么?我最初使用cin << celestial
,它适用于没有空格的字符串(但我仍然得到一个错误)。现在使用getline
,它根本不起作用
你必须正确使用getline:
cin.getline(celestial);
编辑:我为完全错误道歉
getline(cin, celestial);
您使用getline的方式是正确的。然而,在第一次使用"cin"之后,您不清理它的缓冲区。因此,当您使用getline时,程序将读取之前存储在cin缓冲区中的内容,然后程序结束。
要解决这个问题,必须在用户输入权重后包含cin.ignore()函数。那就是:
cin >> weight;
cin.ignore(numeric_limits<streamsize>::max(), 'n');
第一个参数表示如果这些字符都不是第二个参数时要忽略的最大字符数。如果cin.ignore()找到第二个参数,它之前的所有字符将被忽略,直到到达它(包括它)。
所以最后的程序看起来像这样:
#include <iostream>
#include <limits>
#define g_earth 9.81
#define g_mercury 3.7
#define g_venus 8.87
#define g_moon 1.63
using namespace std;
int main (void)
{
float wt_on_celestial, g_ratio;
double weight;
cout << "What is your weight? ";
cin >> weight;
cin.ignore(numeric_limits<streamsize>::max(), 'n');
string celestial;
cout << "Select a celestial body: ";
getline(cin, celestial);
cout << "n";
if (celestial == "Mercury")
{
g_ratio = g_mercury / g_earth;
wt_on_celestial = g_ratio * weight;
cout << "Your weight on Mercury would be " << wt_on_celestial << " kilograms.";
}
else if (celestial == "Venus")
{
g_ratio = g_venus / g_earth;
wt_on_celestial = g_ratio * weight;
cout << "Your weight on Venus would be " << wt_on_celestial << " kilograms.";
}
else if (celestial == "The moon")
{
g_ratio = g_moon / g_earth;
wt_on_celestial = g_ratio * weight;
cout << "Your weight on the moon would be " << wt_on_celestial << " kilograms.";
}
return 0;
}
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 当用户超过按钮点击限制时报告
- Visual C++(VS2017)中用户定义的转换不明确
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何从用户那里获取方程的输入并在 c++ 中对其进行评估
- 如何在用户定义的函数中实现短路评估
- 如何在c++中正确评估用户输入