I'm trying to populate a 2D char array from a text file that looks like:
Bob
Jill
Mike
Steven
and I'm not sure how to do this with different lengths of characters in each line. Here is my code:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
char names[4][7];
string fileName = "names.txt";
ifstream inFile(fileName);
while(!inFile.eof()){
for(int i=0; i<4; i++){
for(int j=0; j<7; j++){
inFile.get(names[i][j]);
}
}
}
for(int i=0; i<4; i++){
for(int j=0; j<7; j++){
cout << names[i][j];
}
}
return 0;
}
and this will print
Bob
Jill
Mike
Steven????????
Where each ? is just a gibberish character. I'm pretty sure this is happening because each line of the text file isn't 7 char long, so it's trying to fill the the rest of the array. What is the correct way to do this? I thought the while(!inFile.eof()){}
would stop this.