按变量数组中的列将一组整数从文本文件读入

read in a set of integers from a text file into by column in to variable arrays

本文关键字:整数 一组 文本 文件 数组 变量      更新时间:2023-10-16

如果我有一个文本文件,看起来像:

4

1 2 3

4 5 6

7 8 9

10 11 12

我想把每列数字读入一个变量x、y和z。所以在阅读之后,z=[3,6,9,12]。

如何解析文本文件以将每列的每一行存储在其自己的变量中?

所以,也许可以将整个文本文件存储为每行带有"/n"的字符串,然后为每行解析x=string[i],y=string[i+1],z=string[i+2]?或者类似的东西。

我认为必须有更好的方法来做到这一点,尤其是当n很大的时候。

~(edit)顶部的第一个数字(本例中为4)决定了文本文件的行数。因此,如果我设置n=4,那么就有一个for循环:for(I=0;I

一次读取一个项目,将每个项目添加到适当的数组:

std::vector<int> x,y,z;
int xx, yy, zz;
while(std::cin >> xx >> yy >> zz) {
  x.push_back(xx);
  y.push_back(yy);
  z.push_back(zz);
}


编辑:响应添加的要求

int n;
if( !( std::cin >> n) )
  return;
std::vector<int> x,y,z;
int xx, yy, zz;
while(n-- && std::cin >> xx >> yy >> zz) {
  x.push_back(xx);
  y.push_back(yy);
  z.push_back(zz);
}

寻求"通用"解决方案(其中n是列数)。在这种情况下,与其单独使用向量变量,不如使用向量中的向量:

std::fstream file("file.txt", ios_base::in);
std::vector< std::vector<int> > vars(n, vector<int>(100));
int curret_line = 0;
while (!file.eof())
{
  for (int i=0; i<n; ++i)
  {
    file >> vars[i][current_line];
  }
  ++current_line;
  // if current_line > vars[i].size() you should .resize() the vector
}

编辑:根据下方的评论更新循环

int i=0, current_line = 0;
while (file >> vars[i][current_line])
{
  if (i++ == n) 
  {
    i = 0;
    ++current_line;
  }
}

这里有一种方法,包括一些基本的错误检查。我们将把小于或大于3个整数的行视为错误:

#include <fstream>
#include <string>
#include <sstream>
#include <cctype>    
std::ifstream file("file.txt");
std::string line;
std::vector<int> x,y,z;
while (std::getline(file, line)) {
    int a, b, c;
    std::istringstream ss(line);
    // read three ints from the stream and see if it succeeds
    if (!(ss >> a >> b >> c)) {
        // error non-int or not enough ints on the line
        break;
    }
    // we read three ints, now we ignore any trailing whitespace
    // characters and see if we reached the end of line
    while (isspace(ss.peek()) ss.ignore();
    if (ss.get() != EOF) {
        // error, there are more characters on the line
        break;
    }
    // everything's fine
    x.push_back(a);
    y.push_back(b);
    z.push_back(c);
}