I'm still very bad at working with files in CPP. I need to read the matrix (we assume that the dimension is known) from a text file. Here is my code:

#include "stdafx.h" #include <iostream> #include <fstream> using namespace std; int main() { ifstream matrix("C:\\Users\\Pavel\\Desktop\\cpp1\\matrix.txt"); float a[60][60]; for (int i = 0; i <= 60; i++) for (int j = 0; j <= 60; j++) matrix >> a[i][j]; for (int i = 0; i < 60; i++) for (int j = 0; i < 60; i++) cout << a[i][j] << " "; system("Pause"); return 0; } 

The problem is that the program reads only the first number from the file and writes it to only (!) The first line of my array. When outputting, the program produces only this first line with the same number. How can I write the entire file to an array, and then output it without problems?

  • The problem code is not visible, try to leave only integers in the file, perhaps the problem is in the decimal separator - pavel
  • @pavel I already tried to change the numbers in the file to integers. Changed dividers with. on but nothing helped. - PavelKas
  • @pavel I want to add that the file itself is not very well compiled. But this does not apply to the first and second lines, since I formatted them. In my place there are two spaces (Array 60x60, therefore difficult) arise. The beginning is as follows: 31.0 11.0 4.2 2.1 0.0 0.0 0.0 0.0 0.0 0.0 - PavelKas
  • @pavel I have now changed the first number to 310. The first cell of the array yielded 310, and the rest - 31. - PavelKas
  • On spaces and translation of lines to this code anyway. Try first 2 on 2 matrix read. - pavel

1 answer 1

Errors:
1. Strict inequality (use < instead of <= ).
2. Forgot to subtract the space that was written to the file.

Corrected version:

 void resolve() { bool isFillFromFile = false; //true для чтения из файла int a[60][60]; if (isFillFromFile) { std::ifstream ist("matrix.txt"); char ch; for (int i = 0; i < 60; i++) // ИСПОЛЬЗУЙТЕ НЕ СТРОГОЕ НЕРАВЕНСТВО!!! for (int j = 0; j < 60; j++) ist >> a[i][j] >> ch; // НЕ ЗАБЫВАЙТЕ ВЫЧИТЫВАТЬ ПРОБЕЛ!!! } else { // Первоначальная генерация файла for (int i = 0; i < 60; i++) for (int j = 0; j < 60; j++) a[i][j] = i + j; } std::ofstream ost("matrix.txt", std::ios_base::trunc); for (int i = 0; i < 60; i++) for (int j = 0; i < 60; i++) { ost << a[i][j] << " "; // ЗАПИСЬ ПРОБЕЛА В ФАЙЛ cout << a[i][j] << " "; } ost.close(); }