oss
oss

Reputation: 115

My 2D array isn't reading my text files and outputting correctly

I want to be able to read in letters from a text file into a 2d array. I'm following all the steps, yet my output isn't at all right.

I've tried to initialize the array, I've tried to change the for loops, I've tried to localize my const int values, but nothing works.

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;



int main()
{
    const int ROWS = 5;
    const int COLS = 3;
    ifstream inFile("grades.txt");

    char gradeArray[ROWS][COLS] = {0};

    inFile.open("grades.txt");

    if (!inFile.is_open())
    {
        cout << "Error opening the file.";
        exit(1);
    }

    for (int i = 0; i < ROWS; i++)
    {
        for (int j = 0; j < COLS; j++)
        {
            inFile >> gradeArray[i][j];
        }
    }
        cout << gradeArray[0][1];


    inFile.close();

system("pause");
return 0;
}

TXT FILE (grades.txt in my resource files)

Edit: The letters each have their own newline. Not sure why they're in the same one.

A R B C H G C F S B A A S E

F

I expect the letter 'R' to be outputted as a test, since that's what I'm asking for in the last cout statement, but I get [ Press any key to continue . . .]. So just a space. Please help. Thanks!

So far I've tried the advice given to me, but it hasn't worked. I'm thinking the file isn't being read correctly? Or the file isn't being outputted correctly...

Upvotes: 1

Views: 98

Answers (1)

Dominic Price
Dominic Price

Reputation: 1146

IIRC doing inFile >> gradeArray[i][j] will capture the whitespace; you should be able to fix this by reading into a string instead which will skip over whitespace; just add #include <string> at the top and then in your loop read into the string and get the grade as the first character, something like

string line;
inFile >> line;
gradeArray[i][j] = line.empty() ? ' ' : line[0];

or whichever character you want to represent missing data.

Upvotes: 1

Related Questions