简体   繁体   English

C ++逐行读取文件(包含空格)中的数据

[英]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). 我正在编写一个9x9的板上游戏(这是一个char 9x9阵列)。 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: 使用getline() ,如下所示:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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