beardeadclown
beardeadclown

Reputation: 377

Weird bug while reading a file C++

When I save the playingBoard array, save prints it properly, however when I try importing the file which save created with import, I get weird output - spaces get removed and replaced with 1s with no obvious logic. (examples are provided below)

minimal reproducible example:

#include <iostream>
#include <fstream>

class Board
{
public:
  char playingBoard[9][9];
  
  Board()
  {
    for (unsigned char i = 0; i < 9; ++i)
      for (unsigned char j = 0; j < 9; ++j)
        playingBoard[i][j] = ' ';
  }

  bool import(std::string filename)
  {
    std::ifstream ifs {filename};
    if (!ifs.is_open())
      return false;

    for (unsigned char i = 0; i < 9; ++i) {
      for (unsigned char j = 0; j < 9; ++j) {
        ifs >> playingBoard[i][j];
        std::cout << playingBoard[i][j] << "|";
      }
      std::cout << std::endl;
    }
  
    ifs.close();
    return true;
  }

  bool save(std::string filename) const
  {
    std::ofstream ofs {filename, std::ios::app};
    if (!ofs.is_open())
      return false;
  
    for (unsigned char i = 0; i < 9; ++i) {
      for (unsigned char j = 0; j < 9; ++j) {
        ofs << playingBoard[i][j];
        std::cout << playingBoard[i][j] << "|";
      }
      std::cout << std::endl;
    }
  
    ofs.close();
    return true;
  }
};

int main()
{
  Board board;
  board.import("filename");
  
  std::cout << std::endl;
  board.playingBoard[1][1] = '1';
  board.save("filename");
}

Upvotes: 3

Views: 175

Answers (1)

Stephen Newell
Stephen Newell

Reputation: 7838

Your problem is that by default, whitespace is skipped with operator >>. You need to use another method of extracting the characters from your file such as the get member function (example below, tested with gcc-9.3.0).

  bool import(std::string filename)
  {
    std::ifstream ifs {filename};
    if (!ifs.is_open())
      return false;

    for (unsigned char i = 0; i < 9; ++i) {
      for (unsigned char j = 0; j < 9; ++j) {
        playingBoard[i][j] = ifs.get();
        std::cout << playingBoard[i][j] << "|";
      }
      std::cout << std::endl;
    }

Output:

$ ./a.out 
 | | | | | | | | |
 |1| | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |

 | | | | | | | | |
 |1| | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |
 | | | | | | | | |

Upvotes: 6

Related Questions