华氏温度到摄氏温度转换器。验证int不是char

时间:2015-08-22 01:09:53

标签: c++ converter temperature

创建了一个将华氏温度转换为摄氏温度的程序。无法验证用户输入是否为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;
}

1 个答案:

答案 0 :(得分:1)

我不确定你对你的意思是什么&#34;继续是或否声明&#34;,所以我写了一个代码,要求用户输入yes来确认转换,否则不输入新的华氏温度值。转换后,程序还要求用户输入yes,如果他/她想要另一次转换,如果用户输入除&#34; yes&#34;之外的任何内容,程序将关闭。

/*********************************************************************
Function to replace part of an XML
**********************************************************************/
function replacePartofXML($element, $methodName, $methodValue, $xml, $newPartofXML)
{
    $xpathstring = "//" . $element . "[@$methodName = \"$methodValue\"]";
    $xml->xpath($xpathstring);

    //$domToChange = dom_import_simplexml($xml->xpath($xpathstring));
    $domToChange = dom_import_simplexml($xml);
    $domReplace  = dom_import_simplexml($newPartofXML);
    $nodeImport  = $domToChange->ownerDocument->importNode($domReplace, TRUE);
    $domToChange->parentNode->replaceChild($nodeImport, $domToChange);

    return($xml);
}

您应该使用#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();忽略任何后续错误数据。例如,&#39; 25tg&#39;&#39; tg&#39;字符被忽略,因为它无效。 &#39; 25&#39;将被接受。

我的回答和代码中的编辑非常受欢迎。