Reputation: 115
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)
A R B C H G C F S B A A S E
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
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