在我的cpp文件,我包括以下内容:如何在C++中正确评估用户输入?
#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
它根本不起作用。
[?为什么的std ::函数getline()跳过格式化提取后输入(http://stackoverflow.com/questions/21567291/why -does-stdgetline跳过输入,后一个格式化的提取) – chris