从输入流读取浮点数而不拖尾"E"

Read float from input stream without trailing "E"

本文关键字:输入流 读取 浮点数      更新时间:2023-10-16

我执行以下操作:

float f;
cin >> f;

在字符串上:

0.123W

数字 0.123 将被正确读取到 f,流读取将在 'W' 上停止。但是如果我们输入:

0.123E

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

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

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

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

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

// 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?