std :: cin用于双精度和字符串 [英] std::cin for double and string

查看:89
本文介绍了std :: cin用于双精度和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行货币兑换练习。程序应读取输入形式的货币金额和名称,并以本国货币返回其价值。

I am doing an exercise on currency exchange. Program should read amount and name of currency form input stream and return its value in national currency.

double amount = 0.0;
std::string currency = " ";

std::cout << "Please enter amount and currency ('usd','eur' or 'rub'):" << std::endl;
std::cin >> amount >> currency;
std::cout << amount << currency << std::endl;

if ( currency == "usd") {
    ...;
} else if ( currency == "eur" ) {
    ...;
} else if ( currency == "rub" ) {
    ...;
} else {
    std::cout << "Input error: unknown currency..." << std::endl;
}

我在此程序中遇到了std :: cin怪异的问题。当键入 100usd或 100rub时,程序分别回显 100usd或 100rub,并继续正常工作。但是,当我键入 100eur时,它回显 0并给出 Input error ...行。同时,如果我键入 100 eur,程序将回显 100eur并正常工作。在前两种情况下,是否放置空格都没有区别。

I've encountered a weird problem with std::cin in this program. When typing in "100usd" or "100rub" the program echoes "100usd" or "100rub" respectively and continues to work normally. But when I type "100eur" it echoes "0" and gives out the "Input error..." line. At the same time, should I type "100 eur", the program echoes "100eur" and works fine. In first two cases it makes no difference if I put whitespace or not.

我在做什么错了?

推荐答案

在100eur的情况下,它认为您正在尝试用科学表示法写一个双精度符号: 1.0e-10 ,但无法解析其余的(因为ur对于指数 section无效)。

In the 100eur case it thinks you're trying to write a double in scientific notation: 1.0e-10 but fails to parse the rest of it (because ur is not valid for the exponent "section").

在其他情况下,它停止在100(到达u / r时),对double有效,因此解析成功。

In the other cases it stops at 100 (when it reaches u/r) which is valid for a double so the parse succeeds.

这篇关于std :: cin用于双精度和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆