[英]Weird bug while reading a file C++
當我保存playingBoard
數組時, save
會正確打印它,但是當我嘗試導入使用import
創建的save
文件時,我會感到奇怪 output - 空格被刪除並替換為1
s,沒有明顯的邏輯。 (示例如下)
最小的可重現示例:
#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");
}
output 首次運行(文件之前不存在,因此只有一個輸出):
| | | | | | | | | |1| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
output 在第二次運行:
1| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 1| | | | | | | | | |1| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
第三次運行 output:
1|1|1| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 1|1|1| | | | | | | |1| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
您的問題是,默認情況下,使用operator >>
跳過空格。 您需要使用另一種方法從文件中提取字符,例如get
成員 function(下面的示例,使用 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| | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.