Putting strings into an array from a file

I'm trying to write the program to read strings into an array. I used the code to see if the file was opening and it did not indicate that it failed(I have since removed that code, just stating that the file opening doesn't seem to be the problem). The file I am using has 4 sentences in it. The cout is not displaying anything. Something appears to be going wrong from after the file opening to the strings not going into the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

char string_file[20];
ifstream in_stream; 
int i=0;
string strings1[20];

main()

{

cout << "What is the name of the file?\n";
cin >> string_file;
in_stream.open(string_file);

while(!in_stream.eof());
{
getline(in_stream,strings1[i]);
i++;
}
cout << strings1[0];

in_stream.close();
}
There are two problems at line 20. The first, the line ends with a semicolon.
that makes it an empty loop
1
2
while(!in_stream.eof())
    ;  // this is the body of the loop 

The other problem is that it's a bad idea to loop on eof. This can be the cause of logic errors, such as infinite loop, or processing the last record more than once.

It's best to put the read operation inside the loop condition:
 
while (getline(in_stream,strings1[i]))


Here, the program also checks that the array capacity is not exceeded:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    char string_file[20];    
    cout << "What is the name of the file?\n";
    cin >> string_file;

    ifstream in_stream(string_file);
    if (!in_stream)
    {
        cout << "file not open: " << string_file << '\n';
        return 1; 
    }
    
    const int ROWS  = 20;
    string strings1[ROWS];
    
    int i = 0;
    while (i<ROWS && getline(in_stream, strings1[i])) 
    {
        i++;
    }
    
    for (int n=0; n<i; ++n)
        cout << strings1[n] << '\n';
    
    in_stream.close();
}


Thanks. This worked
Topic archived. No new replies allowed.