如何在c++中正确评估用户输入

How to correctly evaluate user input in C++?

本文关键字:评估 用户 输入 c++      更新时间:2023-10-16

在我的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;
}