Trying to read some characters from a text file into a 2d array but when I print my array, there are some junk characters...
Here is a screenshot of my text file http://prntscr.com/jg8v1f
and the output http://prntscr.com/jg8vl8
Thank you!
It's more portable for main to return an int instead of being void.
You are checking for source.fail() before you even try to open the file!
When reading the file character-by-character, you are not taking into account the newline characters. I would just skip whitespace generally. The easiest way to do that is to use source >> b; instead of source.get(b).
BTW, it's generally better to use spaces instead of tabs since people's tab settings may be different from yours. The standard "tab" size these days is 4 spaces (definitely not 8!).
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main() {
char A[8][8];
char b;
ifstream source("Easy.txt");
if (!source) {
cerr << "error!!\n";
exit(1);
}
for (int r = 0; r < 8; r++)
for (int c = 0; c < 8; c++) {
source >> b;
switch (b) {
case'#':
case'.':
case'a':
A[r][c] = b;
break;
default:
cerr << "bad character in file: " << b << '\n';
exit(1);
}
}
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++)
cout << A[r][c];
cout << '\n';
}
// ifstreams automatically close when they go out of scope
// (that's the magic of a destructor!)
}
It's more portable for main to return an int instead of being void.
You are checking for source.fail() before you even try to open the file!
When reading the file character-by-character, you are not taking into account the newline characters. I would just skip whitespace generally. The easiest way to do that is to use source >> b; instead of source.get(b).
BTW, it's generally better to use spaces instead of tabs since people's tab settings may be different from yours. The standard "tab" size these days is 4 spaces (definitely not 8!).
Great this worked for this specific code but what if I exchanged the 'a' character with a ' ' character (space) how could I make it work?