read file by fstream

Write your question here.
I want to devide the text in file data.txt into an array of char*( mean i use the pointer char** q) by the way line 1 for q[1], line 2 for q[2] and.... but i don't know why it not work can everyone help me ??? :(
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
34
  char **q;
   const int SIZE = 10000;   
   char input[SIZE];      
   fstream nameFile;    
   int n=0;
   
   nameFile.open("data.txt", ios::in); 
   if (!nameFile) 
   { 
      cout << "ERROR: Cannot open file.\n"; 
   } 
   nameFile.getline(input, SIZE);  //Dùng kí tự mặc định \n như kí tự kết thúc. 
   while (!nameFile.eof()) 
   { 
      n++;
      nameFile.getline(input, SIZE);  //Chỗ này cũng vậy. 
   } 
   q=new char*[n]; //cấp phát động cho mảng q;
   for(int i=0;i<n;i++)
	{ 
		  q[i]= new char[SIZE];
	}
   int i =0;
   nameFile.clear();
   nameFile.seekg(0,nameFile.beg);
   while (!nameFile.eof()) //ghi vào từng hàng tương ứng với từ mảng kí tự q1,q2,..
   { 
      nameFile.getline(q[i++], SIZE);
   } 
   for(int i=0;i<n;i++)
	{ 
		  gets(q[i]);
	}
   nameFile.close(); 
Last edited on
Line 13 you loop through reading the file trying to determine how many 10k blocks to allocate until you reach eof.

Line 24 you attempt to loop through the file again actually reading the blocks, but the eof flag is still set from before so this loop wont execute. You need to call nameFile.clear() to clear the error flags on the file. Also, the file position is still set to eof. You need to call nameFile.seekg(ios_base::beg) to reset the file position back to the beginning.

Last edited on
i used as you said and it still have the problem haizzzz so crazy i spent alot of time on it
Topic archived. No new replies allowed.