简体   繁体   中英

C++ Reading data from a file (containing spaces) line by line

I'm programming a game on a board 9x9 (which is a char 9x9 array). I wrote a method that saves the current game state in a file going according to the scheme bellow:

board.plansza[0][0]
board.plansza[0][1]
board.plansza[0][2]
board.plansza[0][3]
(...)
*points in int*

(Where every line is just a one character/space/number)

Now I need a method that's gonna read this file and put the data back in the same kind of array (if someone decided to stop playing, saved the game and then wanted to continue from previous state) as well as the variable for points. The problem is that some of the lines in a saved file are just a space (' ') and all the methods I've tried are failing to read it properly because of that.

The latest way I tried (and failed):

for (int i = 0; i < ROZMIAR; i++){
        for (int j = 0; j < ROZMIAR; j++){
            zapis << board.plansza[i][j] << endl;
        }
    }

zapis << user.pkt << endl;

How do I read a file line by line if some lines contain only a space (which I don't want to ignore)?

Use getline() , like this:

#include <fstream>
#include <string>

int main()
{
  std::ifstream infile("thefile.txt");
  std::string line;
  char matrix[10][2];
  int i = 0;
  while(std::getline(infile, line))
  {
      std:cout << line << std::endl;
      if(line .find_first_not_of(' ') != std::string::npos)
      {
          // There's a non-space.
          matrix[i++][0] = line[0];
      }
  }
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM