简体   繁体   中英

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

I'm trying to create a battleship program that reads in a 25x25 grid of characters from a text file and puts the info into a 2D array. I've been able to set up the array and read in the info, but for some reason my first nested loop is reading the entire file instead of just one line like I intend. I have tried using .get() , .getLine() , .peek() , etc. with no luck. I'm not sure if I'm using the >> operator incorrectly or if there is a logic error in the loops. Below is the code for my program.

#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;
}

Please let me know if you have any questions.

You should enable and read the warnings. The compiler says

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

After you fix it, it should work.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM