0

I want to read a list of names from a text file like this

Johnny
Bertha
Arty

And put them into a 2-D array with the amount of rows corresponding with the amount of names on the list, in this example 3; and the amount of columns corresponding with the maximum amount of characters to a name, let's say 10.

The array I want to end up with should be sized like this.

names[3][10]

The code I have is broken in the sense that it does not distinguish the line breaks and just fills the array as soon as possible, I want to end up filling the extra space in a row of the array with null characters so the array looks like this.

[J][o][h][n][n][y][\0][\0][\0][\0]
[B][e][r][t][h][a][\0][\0][\0][\0]
[A][r][t][y][\0][\0][\0][\0][\0][\0] (3 rows and 10 columns here)

I used .get but think I need to use the .getline function but I am lost as how I would use it in a nested for loop properly, or is it simpler? Here is the code fragment where I read the names from a text file (10 rows and 9 columns here)

while (! file1.eof()){
for (int i = 0; i < 10; i++){
    for( int j = 0; j < 9; j++){
temp = file1.get();

names[i][j] = temp;
}
}}
steakfry
  • 21
  • 4
  • First of all, please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) Then consider using `std::vector` and `std::string` which will make your life (and the code you're having) *much* easier. In fact, if the file only contain single words on each line, then your reading code could be replaced by a single line. – Some programmer dude Jan 31 '19 at 03:34
  • No dude I know ahahaha I am not allowed to tho – steakfry Jan 31 '19 at 03:35
  • Prefer `std::string` if you are allowed to use it, but if you can't, you may find that [`cin.getline`](https://en.cppreference.com/w/cpp/io/basic_istream/getline) does a lot of the work for you. – user4581301 Jan 31 '19 at 03:36
  • You still don't need to read character by character. Use the [`getline`](https://en.cppreference.com/w/cpp/io/basic_istream/getline) member of the input stream to read the whole lines. – Some programmer dude Jan 31 '19 at 03:37
  • how do I know what line .getline will be reading from? and can I just do something like names[0] = file1.getline()? how do I specify the row as a character array? @Some programmer dude – steakfry Jan 31 '19 at 03:40
  • 2
    The "row of characters" is passed as an argument to the `getline` function, which reads a line and then fills in the array. And since you have a fixed-size array use a normal `for` loop. – Some programmer dude Jan 31 '19 at 03:43

0 Answers0