end of file found to soon

why my c++ program find eof when there are more characters to be read?
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
void step2()
{
	 ifstream in ("D:\\code\\out1.txt", fstream::in);
	 ofstream out ("D:\\code\\out2.txt",fstream::out);

	char *s;
	s = new char[300];
	string str,aux;
	size_t pos, pos1;

	cout<<"Step2";
	while ( (in.eof())==0)
	{	
		in.getline(s,300); 
		str.assign(s); 
		if ((pos=str.find("on env"))!=string::npos) 
		{	
			out<<"void ";
			pos=str.find_first_of(" ",pos+4);
			pos1=str.find_first_of(" ",pos+1);
			aux.assign(str,pos+1,pos1-pos-1);
			out<<aux<<"()\n";
		}
		else out<<s<<"\n";
	}
	in.close();
	out.close();
	delete [] s;
}

it stops somewhere in the middle of a line...
I made a few changes to your code which may fix your issue.

First, there is no need to use a char array. You can use std::getline() function to read directly into a std::string.

Secondly, you should not loop on in.eof(). It is better to loop on std::getline() because that means you only execute the code in the loop if the read was successful.
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
void step2()
{
	ifstream in("D:\\code\\out1.txt", fstream::in);
	ofstream out("D:\\code\\out2.txt", fstream::out);

	// No need to use char arrays
	//char *s;
	//s = new char[300];

	string str, aux;
	size_t pos, pos1;

	cout << "Step2";
//	while((in.eof()) == 0) // don't loop on eof()
	while(std::getline(in, str)) // read directly into string
	{
		// only gets here if read was successful
//		in.getline(s, 300);
//		str.assign(s);
		if((pos = str.find("on env")) != string::npos)
		{
			out << "void ";
			pos = str.find_first_of(" ", pos + 4);
			pos1 = str.find_first_of(" ", pos + 1);
			aux.assign(str, pos + 1, pos1 - pos - 1);
			out << aux << "()\n";
		}
		else
			out << s << "\n";
	}
	in.close();
	out.close();
//	delete[] s; // no longer needed
}
Topic archived. No new replies allowed.