i have three integers per line in a text file but when i read a file it prints four integers

Code:

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
	int clas;
	ifstream inf;
	inf.open("kash.txt");
	do
	{
		inf>>clas;
		cout<<clas;
	}
	while(!inf.eof());
}

here is the file kash.txt (no enter after the 3rd integer)
1
2
3

and why am getting the result as
1233

Edited 6 Years Ago by haseeb1431: n/a

Hi there,your case is a common one; i tried your code but used int main() instead ofvoid main() and i got 123 as my output. This is why good old coders say" use int, never use void" for your main()!!

The loop is wrong. eof() is unnecessary and its causing the problem.

while( inf >> class)
{

}

what if i have many variables to read

Hi there,your case is a common one; i tried your code but used int main() instead ofvoid main() and i got 123 as my output. This is why good old coders say" use int, never use void" for your main()!!

void main() has nothing to do with this problem. The problem is with the logic of the loop, not how main() was declared. But you are right -- it should be int main()

what if i have many variables to read

A couple ways to do it

while( inf >> a >> b >> c ... )
{
}

If a lot of variables

while( inf>> a)
{
    inf>> b >> c ...
}

void main() has nothing to do with this problem. The problem is with the logic of the loop, not how main() was declared. But you are right -- it should be int main()


A couple ways to do it

while( inf >> a >> b >> c ... )
{
}

If a lot of variables

while( inf>> a)
{
    inf>> b >> c ...
}

The reason I said int main() was the cause was that I copied and pasted the original code from this site, changed void to int and then compiled it, and the result was 123. If it's not the cause , however,then pardon my mistakes.

The reason I said int main() was the cause was that I copied and pasted the original code from this site, changed void to int and then compiled it, and the result was 123. If it's not the cause , however,then pardon my mistakes.

int or void main was not the cause of your differing results.

I'd bet that when you created the data file, you did not end it with a newline.

That is, you typed 1 2 3 and right there saved the file.
or you did

1
2
3

and immediately saved.

Had you put a newline after the last data value, then saved, you would get the sam 1233 result as the OP.

This article has been dead for over six months. Start a new discussion instead.