0

I have a file named "t.txt" which contains:
1 2 3 4 5 6 7
8 9 0

Now I want to create two arrays that contain the entries of that individual line like: arr1[7]={1,2,3,4,5,6,7}; arr2[3]={8,9};

Now if there are n number of lines in "t.txt" then I want to create n arrays that contain contents of that individual line.

I don't want to use strings and multi-dimensional arrays.

`

#include <iostream>
#include <fstream>
using namespace std;

int main(){

ifstream input_file;
input_file.open("t.txt");

char arr1[50]={0};
char idata;

int c =0,line_c=1;
while (!input_file.eof())
{
  
    
     input_file.get(idata);
    c++;

    if (idata == '\n')
    {
        c = 0;
        line_c++;
    }

//cout<<"lc"<<line_c<<"sc"<<c<<"ec"<<idata;
    
    
}



return 0 ;
} 





`

  • 1
    You can't use arrays in this context. The size of the array must be known at compile time, but you can't retrieve the sizes without reading the file first. Consider using `std::vector` instead. – Ranoiaetep Nov 27 '22 at 11:29
  • Just use a `std::vector>` for storing the data. Also using `std::getline` would be easier. Furthermore the stream realizes it's at the end of file ***after*** trying to read past the end of the file, not after a extraction operation that reads to the end of the file, so doing the `eof` check there is incorrect. Furthermore there are other ways the input stream can end up in a invalid state, e.g. if `t.txt` doesn't exist and in that case you just end up with an infinite loop... – fabian Nov 27 '22 at 11:32
  • There's a question about the eof issue here btw: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons – fabian Nov 27 '22 at 11:34

0 Answers0