Mar 26, 2013 at 4:46pm UTC
Hello everyone, ive written a program to read inputs in a text file. The file named Input.txt contain integers 2 3 and 4. My program is as follows:
#include<iostream>
#include<cstdlib>
#include<fstream>
using namespace std;
int main ()
{
int x,y,z;
ifstream f;
f.open("Input.txt");
f>>x>>y>>z;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
cout<<"z="<<z<<endl;
f.close();
system("pause");
return 0;
}
the program is outputing x=2293616 , y=0 and z=0 instead of x=2, y=3 and z=4.
Can someone hint me on the problem?
Mar 26, 2013 at 5:02pm UTC
There is an error on opening the file. What does this mean?
In the file i have written 2 3 4 with the spaces.
Mar 26, 2013 at 5:10pm UTC
Maybe it just cannot find file? Compile your program, copy resulting exetuable in separate folder, place your file in it, make sure that it realy have name "Input.txt", run your exetuable.
Mar 26, 2013 at 5:21pm UTC
Oh man... its not working. I did all you said. it comes up with the same output.
You think it is a problem with the compiler i use. Its Dev c++.
Mar 26, 2013 at 5:29pm UTC
Where did you insert check for is_open?
Do Input file really named "Input.txt"?
There is nothing wrong with the code, problem is somewhere else
Mar 26, 2013 at 5:32pm UTC
MiiNiPaa , ive written another program to read from a text. To write the text ive used this program which worked perfectly
#include<iostream>
#include<cstdlib>
#include<fstream>
using namespace std;
int main ()
{
int x;
ofstream f;
f.open("text.txt");
cout<<"Enter Values in the file:";
while(x!=-1)
{
f<<x<<"";
cin>>x;
}
f.close();
system("pause");
return 1;
}
and to read the inputs to that file i used this program
#include<iostream>
#include<cstdlib>
#include<fstream>
using namespace std;
int main()
{
int y;
ifstream f;
f.open("text.txt");
while(!f.eof())
{
cout<<y<<"";
f>>y;
}
f.close();
system("pause");
return 0;
}
instead of outputting the contents of the file. Its giving me the same output as for the first post 2293616.
Any hint on that one?
Mar 26, 2013 at 6:03pm UTC
Please put your code inside code tags, so that it displays properly.
In that second program, you're outputting the value of y before you read anything into it.
Also, your output is going to look weird because you're simply displaying each number after the last with no whitespace between them, so it's going to be hard for you to read.
Mar 26, 2013 at 6:18pm UTC
Thanks for the hint about the code tags ... :) MikeyBoy
Im new here ^^"