I am a beginner in programming and I am trying to make a code that reads 2 numbers from a file and then displays it in the output window on turbo c++. My code only reads the first number and produces incorrect output for the second number.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
int x, y;
clrscr();
ifstream inFile;
ofstream outFile;
inFile.open("prac.txt");
while(!inFile.eof())
inFile >> x >> y;
cout << x << " " << y;
inFile.close();
}
The file contains the numbers: 2
3
Output : 2
0
Output when called as a function: 2
-28903
which is very different if I call it as a function compared when its in main which is what I was supposed to be doing
I was just using it in main to see what happens.
Sorry, but our teacher wanted us to learn in Turbo c++ so I don't really have choice with the compiler.
The std::cout
should be inside the while loop:
while(!inFile.eof()){
inFile >> x >> y;
cout << x << " " << y;
}
Try using infile>>x>>y inside the while loop condition like this
while(infile>>x>>y)
then use the cout statement in the loop.
来源:https://stackoverflow.com/questions/34489267/how-to-read-data-from-files-in-turbo-c-4-0