繁体   English   中英

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

[英]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;

可以说它仅在文件中获取第一个值的范围内起作用。 如何获得要输入所有值的数组? 我调试了程序,可以确认该行具有所有必需的值; 但float数组没有。 请帮忙,谢谢!

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() 您不能使用sizeof ,因为ar是一个指针,而不是数组。

最简单的选择是使用标准库及其流。

$ 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语句的stringstream将带有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 );
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM