无法将整数从文件读取到矩阵

Can't read integer from file to matrix

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

我必须从文件中读取一个未知大小的数字数组,并将其保存为矩阵。代码必须尽可能紧凑,这就是为什么我不想将文件读取为字符串,然后将其转换为int

int main() 
{   
    ifstream infile("array.txt");
    int n, counter = 0, **p;
    while (!infile.eof()) {
        counter++;
    }
    counter = sqrt(counter);
    cout << "counter is " << counter << endl;
    p = new int*[counter];
    for (int i = 0; i < counter; i++)
        p[i] = new int[counter];
    while (!infile.eof()) {
        for (int i = 0; i < counter; i++) {
            for (int j = 0; j < counter; j++)
                p[i][j] = n;
        }
    }
    for (int i = 0; i < counter; i++) {
        for (int j = 0; j < counter; j++) {
        cout << p[i][j] << " ";
        }
        cout << endl;
    }
    _getch();
    return 0;
} 

这是我的代码,它是为一个正方形矩阵编写的。问题是,我无法在第二次读取文件以将数字保存到矩阵中。

您的代码中有很多问题。一个很大的问题是,你有几个无限循环,甚至没有从文件中读取。一个更大的问题是您没有使用C++构造。我已经编写了一个小程序,它可以使用更多的C++概念来完成您想要做的事情。在这种情况下,您应该使用std::vector——它们将为您处理所有的动态大小调整。

测试.cc

#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
#include <string>
// Nobody wants to write `std::vector<std::vector<int>>` more than once 
using int_matrix = std::vector<std::vector<int>>;
void populate_matrix(int_matrix& mat, const std::string& line) {
  int num;
  std::stringstream ss(line);
  std::vector<int> row;
  // Push ints parsed from `line` while they still exist
  while(ss >> num) {
    row.push_back(num);
  }
  // Push the row into the matrix
  mat.push_back(row);
}
// This is self-explanatory, I hope
void print_matrix(const int_matrix& mat) {
  size_t n = mat.at(0).size(); 
  for(size_t i = 0; i < n; ++i) {
    for(size_t j = 0; j < n; ++j) {
      std::cout << mat.at(i).at(j) << " ";
    }
    std::cout << std::endl;
  }
}
int main(int argc, char** argv) {
  int_matrix mat;
  // Pass the file as a command-line arg. Then you don't need to worry about the path as much.
  if(argc != 2) {
    std::cout << "Number of arguments is wrongn";
    return EXIT_FAILURE;
  }
  // Open file with RAII  
  std::ifstream fin(argv[1]);
  std::string line;
  // Handle each line while we can still read them
  while(std::getline(fin, line)) {
    populate_matrix(mat, line);
  }
  
  print_matrix(mat);
  return EXIT_SUCCESS;
}

此代码假定文本文件如下所示:

numbers.txt

1 2 3 
4 5 6 
7 8 9 

即每行具有由空白分隔的n个数字的n行。

要编译并运行此代码,您可以按照以下步骤操作:

13:37 $ g++ test.cc -std=c++14
13:37 $ ./a.out /path/to/numbers.txt 

据我所见,程序在文件中运行一次,之后您运行另一个while循环来读取文件。当你读取一个文件时,它就像你的"光标"向前移动。因此,基本上,如果达到末尾,则必须将光标重置回文件的开头

您可以使用seekg(0)将光标向后设置。(http://www.cplusplus.com/reference/istream/istream/seekg/)