无法将整数从文件读取到矩阵
Can't read integer from file to matrix
我必须从文件中读取一个未知大小的数字数组,并将其保存为矩阵。代码必须尽可能紧凑,这就是为什么我不想将文件读取为字符串,然后将其转换为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/)
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中