华氏到摄氏转换器.验证int而不是char



创建了一个将华氏温度转换为摄氏温度的程序。在验证用户输入是否是int时遇到麻烦。我认为问题是"if (!cin)"行。

#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
float f, c;
string choice;
do{
    cout << "Enter a Fahrenheit temperature to convert to Celsius:" << endl;
    cin >> f ;
    if ( !cin ) {
        cout << "That is not a number..." << endl;
    }
    else if (f < -459.67) {
        cout << "That is not a Fahrenheit temperature..." << endl;
    }
    if ( f >= -459.67) {
        c = (( f - 32) * 5.0)/9.0 ;
        cout << fixed ;
        cout << setprecision(2) << "Celsius temperature is: " << showpos << c << endl;
    }
    cout << "Would you like to convert another? If so, enter Yes" << endl;
    cin >> choice ;
}while ( choice == "Yes" || choice == "yes" );
return 0;
}

我不确定你的"Continue yes or no statement"是什么意思,所以我写了一个代码,要求用户输入yes来确认转换,否则输入no来输入一个新的华氏度值。转换后,程序还要求用户输入yes,如果他/她想要另一个转换,如果用户输入除"yes"以外的任何内容,程序将关闭。

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
    bool Continue = true;
    while (Continue == true)
    {
        double f, c;
        cout << endl << "Enter a Fahrenheit temperature to convert to Celsius:" << endl << endl;
        while (!(cin >> f))
        {
            cout << endl << "Invalid Input. " << endl << endl;
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
        }
        while (f <= -459.67)
        {
            cout << "Invalid Input. " << endl;
            cin.clear();
            cin.ignore();
            cin >> f;
        }
        cout << endl << "Continue? Type yes to proceed conversion, Otherwise type no." << endl << endl;
        string confirmation;
        cin >> confirmation;
        while (confirmation != "yes" && confirmation != "no")
        {
            cout << endl << "Input not recognized. try again." << endl << endl;
            cin >> confirmation;
        }
        if (confirmation == "yes")
        {
            c = ((f - 32) * 5.0) / 9.0;
            cout << fixed;
            cout << endl << setprecision(2) << "Celsius temperature is: " << showpos << c << endl;
            cout << endl << "Another convertion? type yes to confirm. " << endl << endl;
            string cont;
            cin >> cont;
            if (cont != "yes")
            {
                Continue = false;
            }
        }
    }
    return 0;
}

你应该使用while循环,这样程序不会停止询问,直到用户输入正确的数据。使用cin.clear();清除用户输入的无效数据。cin.ignore();忽略任何后续的错误数据。例如,'25tg', 'tg'字符被忽略,因为它是无效的。"25"将被接受。

非常欢迎对我的答案和所提供的代码进行编辑。

您可以使用一个函数来检查输入是否是数字....

应该是这样的:

    bool isFloat( string myString ) {
    std::istringstream iss(myString);
    float f;
    iss >> noskipws >> f; // noskipws considers leading whitespace invalid
    // Check the entire string was consumed and if either failbit or badbit is set
    return iss.eof() && !iss.fail(); 
}

最新更新