.txt to 2d array

Feb 22, 2019 at 7:16pm
The code doesn't show any errors but doesn't show any results also

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string S [30] [6];
    string L;
    ifstream file;
    string s;
    string m;
    cin >> m;
    int count = 0;
    file.open("sample.txt");
   while ((getline(infile, l)))
       count++;
    infile.seekg(0, ios_base::beg);
    for (int i=0; i < count; i++)
    {
        for (int j=0; j < 6; j++)
        infile >> s[i][j];
    }
    for (int k = 0; k < count; k++)
    {
        for (int x = 0; x < 6; x++)
            cout << s[k][x];
    }
}

Can someone please tell me what did I do wrong?
Last edited on Feb 22, 2019 at 7:54pm
Feb 22, 2019 at 7:25pm
Line 14: You don't check that your open succeeded. If the open fails, your program will execute, but not show any results.

Line 15: When you reach eof, infile's eof bit will be set. You don't clear the stream state, so none of the subsequent read operations will succeed.
Feb 22, 2019 at 7:31pm
Thank you for answering
I added your comments to my code through
1
2
if (infile.fail())
        cout << "code is not working";


About your other comment, I am not sure I understand what you mean
Last edited on Feb 22, 2019 at 7:32pm
Feb 22, 2019 at 7:49pm
Lines 15-16: You're reading the file until you reach EOF. When you attempt to read past the last record, the EOF state bit is set for the file. You position to the beginning of the file and start reading again (line 21). Those reads are going to fail because the EOF state bit is still set. Before line 17, you need to call infile.clear(); to clear the EOF state bit.
http://www.cplusplus.com/reference/ios/ios/clear/
Feb 22, 2019 at 7:53pm
Thank you so much
Topic archived. No new replies allowed.