从输入流读取浮点数而不拖尾"E"
Read float from input stream without trailing "E"
我执行以下操作:
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?
相关文章:
- 如何忽略输入流中的某些字符?
- 使用字符串流读取整数并将它们相加
- C++如何正确实现并行IF流读取
- 失败后可以继续从流读取吗?
- C++输入流.与 cin unget() 函数有点混淆
- 从输入流中读取行,并能够跳过块
- 使用 Visual Studio 代码读取 C++ 中的输入流时出错
- 是否可以从输入流中'throw away'读取值?
- 从输入流读取浮点数而不拖尾"E"
- 如何将换行符按钮更改为空格以完成从输入流的读取
- 如何读取存储在输入流缓冲区中的字符数
- 是否可以使用输入流读取无穷大或NaN值
- 读取输入流而不提取
- 一次从输入流读取一个单词到字符数组
- std::getline()从流中读取格式化的输入后读取错误的数据
- 如何从输入流读取到文件流
- C++文件输入流:读取"large"整数
- 实现一个从输入流中读取一系列值作为参数的函数
- 重载输入流运算符>>用于从文件中读取对象
- 无法从输入流读取字节数据