簡體   English   中英

如何從 C++ 中的文本文件一次讀取一個字符?

[英]How to read in one character at a time from a text file in C++?

我正在嘗試創建一個戰艦程序,該程序從文本文件中讀取 25x25 的字符網格並將信息放入 2D 數組中。 我已經能夠設置數組並讀取信息,但由於某種原因,我的第一個嵌套循環正在讀取整個文件,而不是像我想要的那樣只讀取一行。 我嘗試過使用.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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM