【问题标题】:Read float from input stream without trailing "E"从输入流中读取浮点数,不带尾随“E”
【发布时间】:2014-02-07 15:02:41
【问题描述】:

我执行以下操作:

float f;
cin >> f;

在字符串上:

0.123W

数字 0.123 将被正确读取到 f,并且流读取将在“W”时停止。但是如果我们输入:

0.123E

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

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

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

【问题讨论】:

  • 你试过 std::cin.ignore 吗?
  • 我的意图是成功读取一个浮点数并留下'E'字符以供进一步阅读。在这里使用忽略有什么意义?
  • 至少在 Mac OS X 上,C 语言标准 I/O 工具接受 0.123E 表示法作为浮点数 0.123 后跟未使用的字母 E。这表明一种选择是使用它,尽管考虑到您使用 C++ 工作,这并不好。在 C++ (g++ 4.8.2) 中工作,我得到了错误。这表明 C++ 标准需要错误,与 C 标准不同——尽管从 C 程序员的角度来看,这似乎是错误的行为——0.123E0.123E- 都应该没问题,停在 E。
  • 吹毛求疵:这不是领先,而是尾随 e

标签: c++ iostream


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2018-10-04
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      相关资源
      最近更新 更多