本文介绍了从输入流读取浮点数,而不在尾随"E"字尾.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行以下操作:

float f;
cin >> f;

在字符串上:

0.123W

数字0.123将正确地读取到f,并且流读取将在"W"处停止.但是,如果我们输入:

Number 0.123 will be properly read to f, and stream reading will be stopped on 'W'. But if we enter:

0.123E

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

operation will fail and cin.fail() will return true. Probably the trailing 'E' will be treated as part of scientific notation.

我尝试cin.unsetf(std::ios::scientific);失败.

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

Is there any possibility to disable treating character 'E' specially?

推荐答案

是的,您必须自己解析.这是一些代码:

Yes, you have to parse it your self. Here is some code:

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

这篇关于从输入流读取浮点数,而不在尾随"E"字尾.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:39