从文件中读取浮点数/单词/符号,并仅将浮点数存储在数组中
Reading floats/words/symbols from a file and ONLY storing the floats in an array C++
我有一个c++编程问题,我被要求从一个包含几个浮点数,单词和符号(例如# ! %
)的文件中读取。从这个文件中,我必须只取浮点数并将其存储到一个数组中。
文本文件可能看起来像这样
<>之前11你好1.0016.01.999之前我知道如何打开文件;它只是抓取只有浮动我挣扎。
您必须使用fscanf()
。
只要你不介意把整数当作浮点数,比如你的文章中的11
,你可以使用以下策略:
- 每次读取一个由空格分隔成字符串的令牌。
- 使用以下几种方法之一从字符串中提取浮点数
- 如果提取成功,则处理浮点数。否则,转到下一个令牌。
下面的代码行应该可以工作。
std::string token;
std::ifstream is(filename); // Use the appropriate file name.
while ( is >> token )
{
std::istringstream str(is);
float f;
if ( str >> f )
{
// Extraction was successful.
// Check whether there is more data in the token.
// You don't want to treat 11.05abcd as a token that represents a
// float.
char c;
if ( str >> c )
{
// Ignore this token.
}
else
{
// Process the float.
}
}
}
我会使用ctype facet将除数字以外的所有内容分类为空白:
struct digits_only : std::ctype<char>
{
digits_only() : std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size, std::ctype_base::space);
if (rc['0'] == std::ctype_base::space)
std::fill_n(&rc['0'], 9, std::ctype_base::mask());
return &rc[0];
}
};
然后使用该facet向流中注入区域设置,然后读取数字:
int main() {
std::istringstream input(R"(
11
hello
1.00
16.0
1.999)");
input.imbue(std::locale(std::locale(), new digits_only));
std::copy(std::istream_iterator<float>(input), std::istream_iterator<float>(),
std::ostream_iterator<float>(std::cout, "t"));
}
结果:11 1 16 1.999
// reading a text file and storing only float values
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
std::vector<float> collection;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
if(checkIfFloatType(line))
{
collection.push_back(std::stof (line));
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
bool checkIfFloatType( string str ) {
std::istringstream iss(str);
float f;
iss >> noskipws >> f;
return iss.eof() && !iss.fail();
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 使用提升将数据从 PyObject 复制到浮点数 *
- 使用浮点数和双精度数的非常小数字的数学
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 我在将 10^18 存储为浮点数时遇到问题
- C++ - 浮点数组在某个非常大的索引之后不存储值
- 如何创建用于存储和返回浮点数数组的结构
- 将浮点数组存储在纹理中,并使用纹理坐标从着色器访问浮点
- 如何将 4 个浮点数的 ps 向量转换为 4 个双精度并存储到 pd 数组
- 在同一行中读取混合输入(字符串/浮点数),并将其存储在数组中
- 使用浮点数存储大量数字
- 存储浮点数的最佳方式
- c++如何从文件中读取浮点数并存储到另一个文件中
- 从文件中读取浮点数并将其存储到数组中
- 从文件中读取浮点数/单词/符号,并仅将浮点数存储在数组中
- 如何在数组中存储浮点数
- 浮点精度 - C++ std::numeric_limits<float>::max() 可以准确地存储在浮点数中并在以后进行比较吗?
- 如何判断双精度浮点数是否可以安全地存储为单精度浮点数