Please tell me how to do it right. I need an array of Char Field [20] [20] filled with characters from a file.

I did the following function:

void Spiel::readFile(std::string fileName) { std::ifstream file(fileName.c_str()); if (!file.is_open()) { std::cerr << "Error opening file: " << fileName << std::endl; exit(1); } std::string line; int a = 0; while (true) { if (a == 21) break; std::getline(file, line); for (int i = 0; i < 20; i ++) { if (line[i] == std::string::npos) { Field[a][i] = '#'; } else { Field[a][i] = line[i]; } } a++; // weiter machen if, wenn Field [i][j] == "B", bx = i, by = j } std::cerr << "Done" << std::endl; } int main(int argc, char** argv) { Spiel spiel; spiel.readFile(std::string(argv[1])); }; 

According to gdb print Field or print line, it gives incomprehensible numbers and signs, but not like letters that are in the readable file. I can not understand what is wrong

  • one
    You would use a debugger, it would be sooner. - VladD
  • what debugger? - Vladimir
  • Some strange array filling algorithm ... Starting from while(true) { if(a==21) ... Reading this brain code is difficult to grasp the point. - PinkTux
  • @PinkTux the intent was such that, on a line, all are considered letters from a file and are stored in Field. The variable a counts the number of lines. When 20 lines were counted, break - Vladimir
  • one
    @ Vladimir: Any, actually. Usually, a debugger is included with the compiler. - VladD

1 answer 1

One question: what did you mean by this line line[i] == std::string::npos ? If I understand correctly, if the string is shorter than 20 characters, then you finish it off with bars, am I right?

In general, it immediately catches the eye that you fill in an array of 20 lines, but you read 21 times, and indeed, why suffer with while(true) , if in fact you still have a cycle with a number of steps known in advance, you should replace for .

Now, it makes sense to check the length of the line as i >= line.length() .

The result is something like this:

 void Spiel::readFile(std::string fileName) { std::ifstream file(fileName.c_str()); if (!file.is_open()) { std::cerr << "Error opening file: " << fileName << std::endl; exit(1); } std::string line; for(int a = 0; a < 20; a++) { std::getline(file, line); for (int i = 0; i < 20; i ++) { if (i >= line.length()) { Field[a][i] = '#'; } else { Field[a][i] = line[i]; } } } std::cerr << "Done" << std::endl; } 

I checked this code on a file with this function itself, it turned out like this:

 #include <iostream># #include <string>### #include <fstream>## #################### void readFile(std::s char Field[20][2 std::ifstream fi if (!file.is_ope std::cerr << exit(1);#### }############### std::string line int a = 0;###### while (true) {## if (a == 21) break;## std::getline for (int i = if (line Fiel