c++ - 如何从 C++ 中的文本文件一次读取一个字符?

标签 c++ fstream

我正在尝试创建一个战舰程序,该程序从文本文件中读取 25x25 字符网格并将信息放入二维数组中。我已经能够设置数组并读取信息,但出于某种原因,我的第一个嵌套循环正在读取整个文件,而不是像我打算的那样只读取一行。我曾尝试使用 .get().getLine().peek() 等,但没有成功。我不确定我是否错误地使用了 >>> 运算符,或者循环中是否存在逻辑错误。下面是我的程序的代码。

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;

char game_map[25][25];


int main()
{

ifstream file("GameMap.txt");    //Opens text file so that data can be read in

for (int i = 0; i < 25; i++) { 
    for (int j = 0; j < 25; j++) {               
        file >> game_map[i][j];
    }
}

for (int i = 0; i < 25; i++) {
    for (int j = 0; j < 25; j++) {
        cout << game_map[i, j];
    }
    cout << "LINE " << i << endl;
}

system("pause");
return 0;
}

如果您有任何问题,请告诉我。

最佳答案

您应该启用并阅读警告。编译器说

warning: left operand of comma operator has no effect [-Wunused-value]
   23 |         cout << game_map[i, j];
      |                          ^

修复后,它应该可以工作。

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;

char game_map[25][25];


int main()
{

ifstream file("GameMap.txt");    //Opens text file so that data can be read in

for (int i = 0; i < 25; i++) { 
    for (int j = 0; j < 25; j++) {               
        file >> game_map[i][j];
    }
}

for (int i = 0; i < 25; i++) {
    for (int j = 0; j < 25; j++) {
        cout << game_map[i][j]; // <-- Fix it
    }
    cout << "LINE " << i << endl;
}

system("pause");
return 0;
}

关于c++ - 如何从 C++ 中的文本文件一次读取一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58290027/

相关文章:

c++ - 如果基类构造函数受到保护,为什么我们不能在派生类函数中创建基类的对象

C++仅覆盖文件段

c++ - 仅覆盖文件的特定部分

c++ - 如何强制 QT Creator 的切换注释功能不跳行

c++ - 将元素添加到未存储的 c++ 类中的 vector

c++ - _ctermid.h : No such file or directory error on mac without Xcode

c++ - 从输入文件中读取多种数据类型

c# - 在线程内 sleep 的替代方法

c++ - 使用 fstream 读出 txt 文件崩溃 .exe

C++:运行我的程序时出现段错误(将文件中的数字输入到数组中)