从输入流中读取float而不引导“E”

时间:2014-02-07 15:02:42

标签: c++ iostream

我执行以下操作:

float f;
cin >> f;

在字符串上:

0.123W

编号0.123将正确读取到f,并且流读取将在'W'上停止。但是如果我们输入:

0.123E

操作将失败,cin.fail()将返回true。可能领先的'E'将被视为科学记数法的一部分。

我尝试cin.unsetf(std::ios::scientific);但没有成功。

是否有可能禁用特殊处理字符'E'?

2 个答案:

答案 0 :(得分:2)

您需要将该值读取为字符串,并自行解析。

答案 1 :(得分:1)

是的,你必须自己解析它。这是一些代码:

// Note: Requires C++11
#include <string>
#include <algorithm>
#include <stdexcept>
#include <cctype>
using namespace std;

float string_to_float (const string& str)
{
    size_t pos;
    float value = stof (str, &pos);
    // Check if whole string is used. Only allow extra chars if isblank()
    if (pos != str.length()) {
        if (not all_of (str.cbegin()+pos, str.cend(), isblank))
            throw invalid_argument ("string_to_float: extra characters");
    }
    return value;
}

用法:

#include <iostream>
string str;
if (cin >> str) {
    float val = string_to_float (str);
    cout << "Got " << val << "\n";
} else cerr << "cin error!\n"; // or eof?