从文件到字符串再到数组读取数字
Reading numbers from file to string to array
我正在从一个文件中读取数字,比如:
1 2 3 4 5
我想把这个数据从一个文件中读取到一个数组中的字符串中,以便进一步处理。以下是我所做的:
float *ar = nullptr;
while (getline(inFile, line))
{
ar = new float[line.length()];
for (unsigned int i = 0; i < line.length(); i++)
{
stringstream ss(line);
ss >> ar[i];
}
}
unsigned int arsize = sizeof(ar) / sizeof(ar[0]);
delete ar;
只要说它只从文件中获得第一个值就足够了。如何让数组输入所有值?我调试了程序,我可以确认行具有所有必要的值;但是浮点数组没有。请帮忙,谢谢!
line.length()
是一行中的字符数,而不是单词/数字/诸如此类的数字。
使用一个可以很容易调整大小的向量,而不是试图篡改指针。
std::vector<float> ar;
std::stringstream ss(line);
float value;
while (ss >> value) { // or (inFile >> value) if you don't care about lines
ar.push_back(value);
}
该大小现在可用作ar.size()
;由于ar
是一个指针,而不是一个数组,所以使用sizeof
是行不通的。
最简单的选择是使用标准库及其流。
$ cat test.data
1.2 2.4 3 4 5
给定文件,您可以使用流库,如下所示:
#include <fstream>
#include <vector>
#include <iostream>
int main(int argc, char *argv[]) {
std::ifstream file("./test.data", std::ios::in);
std::vector<float> res(std::istream_iterator<float>(file),
(std::istream_iterator<float>()));
// and print it to the standard out
std::copy(std::begin(res), std::end(res),
std::ostream_iterator<float>(std::cout, "n"));
return 0;
}
我早些时候遇到了这个问题,当时我想从文件中逐行提取数据来填充我想要使用的sql数据库。这个特定问题有很多解决方案,例如:
该解决方案使用带有while语句的字符串流将文件中的数据放入带有while声明的数组
//编辑
- 带有getline的While语句
//这个解决方案不是很复杂,而且很容易使用。
新改进的简单解决方案:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream line;
line.open("__FILENAME__");
string s;
vector<string> lines;
while(getline(line, s))
{
lines.push_back(s);
}
for(int i = 0;i < lines.size();i++)
{
cout << lines[i] << " ";
}
return 0;
}
编译代码以检查-http://ideone.com/kBX45a
atof
怎么样?
std::string value = "1.5";
auto converted = atof ( value.c_str() );
相当完整:
while ( std::getline ( string ) )
{
std::vector < std::string > splitted;
boost::split ( splitted, line, boost::is_any_of ( " " ) );
std::vector < double > values;
for ( auto const& str: splitted ) {
auto value = atof ( str.c_str() );
values.push_back ( value );
}
}
相关文章:
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 如何从文件中读取数字并在数组中使用它们?
- 使用模板化函数从CSV文件中读取数字
- 根据数字在 c++ 中作为矩阵的位置从文件中读取数字
- 如何从文件中读取数字序列?
- 如何允许我的程序成功读取数字包含的文件
- 如何仅从C 中的文本文件中读取数字
- 从没有分隔符 C++ 的文件读取数字出现次数
- 读取数字并转换为单词
- 从文件,特定行中仅读取数字
- 从TextFile中读取数字,并检查它们是否在范围内
- C 从文本文件中读取数字,忽略注释
- 从文件读取数字列表到动态数组
- 我正在尝试从文件中读取数字
- 从txt文件中读取数字,添加一些数字,然后在c ++中将其重写为其他文件
- C++如何从文件中读取数字并将其分配到数组中的相应位置
- 读取数字的文本文件,并存储在C++的整数数组中
- 从文件中读取数字
- 从文本中读取数字并输出平均值