file handling in c++

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?
Check if file really opened:
1
2
if (!f.is_open())
    std::cout << Error opening file;
There is an error on opening the file. What does this mean?
In the file i have written 2 3 4 with the spaces.
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.
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++.
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
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?
1) there is code tags on the right which looks like that <>. Use them to post code.
2)
1
2
3
4
5
while(!f.eof())
{
    cout<<y<<"";
    f>>y;
}

y is uninitialized when you use it first time.
3) Same for outputting data: first value will be garbage.
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.
Thanks for the hint about the code tags ... :) MikeyBoy
Im new here ^^"
Topic archived. No new replies allowed.