我正在尝试创建一个战舰程序,该程序从文本文件中读取 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/