从文件到字符串再到数组读取数字

Reading numbers from file to string to array

本文关键字:读取 数字 数组 字符串 文件      更新时间:2023-10-16

我正在从一个文件中读取数字,比如:

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声明的数组

//编辑

  1. 带有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 );
   }
}