簡體   English   中英

c++ 如何將 6e(或任何帶有 e 的數字)解釋為輸入?

[英]How does c++ interpret 6e(or any number with e) as an input?

當運行此代碼並輸入 6e 或任何其他帶有 e 的數字時,程序無法識別它並以 else 狀態結束。 我在這里做錯了什么?

#include "../std_lib_facilities.h"

int main() {
    cout << "Please enter amount of money followed by the currency name:" 
        + "y for yen, p for pound or e for euro, like 3.40e. \n"
        << "This app will convert it to dollars. \n";
    double amount;
    char currency = ' ';
    double dollars;
    cin >> amount >> currency;

    cout<<"amount:  "<< amount <<"\n";
    cout<<"currency :" << currency<<"\n";

    if (currency == 'y'){
        cout <<amount<<"Yuan = "<< amount * 0.15<<" dollars";
    }
    else if (currency == 'e') {
        cout << amount << "Euro = " << amount * 1.18 << " dollars";
    }
    else if (currency == 'p') {
        cout << amount << "Pounds = " << amount * 1.29<< " dollars";
    }
    else {
        dollars = 0;
        cout << "Unknown currency\n";
    }
}

operator >>讀取由空格分隔的元素(或直到無法解析的字符)。

6e不能被解析為double 6e值(但e是科學記數法的有效字符,因此它被消耗),並且cin進入失敗狀態並且每個后續>>調用都失敗。

對於cin >> amount >> currency; 工作輸入應該看起來像6 e (或6e0e )。

如果您希望6e也用作輸入,則需要將其作為字符串讀取(或使用getline讀取整行)並getline解析(例如提取和后綴字符,然后將剩余數字解析為double )。

另請參閱這個類似的問題: 從沒有“E”的輸入流中讀取浮點數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM