can not read from a file

Hıı everyone,
ı am new to c++ , ı am trying to reading from a file but ıt does not work can you help me why ı can not read from a file this is my code and ı am using vs2010.

int main()
{ string al;
int a;
ifstream a_file;
a_file.open("pe.txt");
a_file>>al;
cout<<al<<endl;
a_file.close();
cin>>a;
return 0;
}
It's possible that your program cannot find the file. pe.txt must be in the "current directory". That is, the directory that you're currently in when you run the program.
try adding this check to see if what kbw wrote its true:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{ string al;
int a;
ifstream a_file;
a_file.open("pe.txt");
if (a_file.is_open())
   cout<<"File opened successfully"<<endl;
a_file>>al;
cout<<al<<endl;
a_file.close();
cin>>a;
return 0;
}

Last edited on
When ı changed the above code segment with this program give me the ''unable to read". However ın the deskop there is a file named as pet.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
int _main()
{string al;
 int a;
 ifstream myfile("pet.txt");
 if (myfile.is_open())
 { while(getline(myfile,al))
 {cout<<al<<endl;
 }
 myfile.close();
 }
 else
	 cout<<"unable to read "<<endl;
cin>>a;}
You mayneed to specify the full path to the file. For example:
 
ifstream myfile("/Users/kbw/work/pet.txt");
Why are posts in this thread being reported? There's nothing wrong with them.
Topic archived. No new replies allowed.