StarSweeper StarSweeper - 1 month ago 18
C++ Question

Why isn't my program inputing chars into 2d array from file?

I'm trying to input chars into a 2d array from a file, but its not putting anything into the array. When I try to print it out I just get a bunch of symbols that look like this - ╠

Here is an example that produces the same error:

test file looks like this:

g g g g g g g g g g
g g g t t t t t t g
g g g t t g t t g g
g t t g g t g g t g
g t t g g t g g t g
g t g t t g t t g g
g t t g g t g g t g
g t t g g t g g t g
g t g t t g t t g g
g g g g g g g g g g


Example that produces same error:

#include<iostream>
#include<string>
#include<fstream>

using namespace std;


int main() {
ifstream inFile;
char myArray[15][15];

inFile.open("C:\test\Ch5p_fa.asc");

int rows = 10;
int columns = 10;

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++) {
inFile.get(myArray[i][j]);
}
}


for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++) {
cout << myArray[i][j] << ' ';
}
cout << endl << endl;
}

inFile.close();

cin.get();

}

Answer

Try this:

int main() {

    ifstream inFile;
    char myArray[15][15];

    inFile.open("C:\\test\\Ch5p_fa.asc", std::fstream::in);   // std::fstream::in allows you to read from the file.

    int rows = 10;
    int columns = 10;

    for (int i = 0; i < rows; i++)  {
        for (int j = 0; j < columns; j++) {
            inFile.get(myArray[i][j]);
            inFile.get();                       // Skeem unwonted char
        }
    }

    inFile.close();

    cin.get();

}

If you need the spaces just make column twice as big.

Comments