2015-09-05 44 views
0

在我的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它根本不起作用。

+5

[?为什么的std ::函数getline()跳过格式化提取后输入(http://stackoverflow.com/questions/21567291/why -does-stdgetline跳过输入,后一个格式化的提取) – chris

回答

0

你必须做出正确使用函数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; 
} 
+0

我很快就意识到我犯了一个错误。虽然我没有看到你的评论,但是无论如何,谢谢你。 –