#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ofstream w("d:/tester.txt");
int f = 1;
int s = 2;
int t = 3;
string x = "hello";
w << f << endl << s << endl << t << endl开发者_高级运维 << x ;
w.close();
ifstream r("d:/tester.txt");
r >> x;
cout << x << endl ;
s = s + 10 ;
r.close();
/* ofstream wa("d:/tester.txt");
wa << s;
wa.close();*/
}
I always get the output equal to 1 .
Why is this so ? When i asked for the string hello
1 gets displayed .
In fact, it is the output you ask for: you are reading the first string token from the file. And that happens to be the number “1” you wrote on the first line into the file.
The streaming operators don’t magically parse your file for the most suitable token; they are simply reading the next available token. And even if they did, “1” would be a perfectly valid choice for a string.
You store consecutively 1 2 3 in your file, then you fetch the first value from the file. Are you surprised that the value is 1? If you want the other values, you must call the stream in functions more than once.
The first line of tester.txt is f
which is 1
.
x is a string, so when you read from tester.txt using r>>x
you get the first line, which is "1"
When you open a stream, you open it in a top-bottom fashion, this meaning that the stream is positioned in the beginning of the first line.
You wrote:
w << f << endl << s << endl << t << endl << x ;
So line the lines are:
- f
- s
- t
- x
And f = 1
, so you are getting what you should be getting.
Isn't that what you would expect, or am I missing something?
You put the values "1" "2" "3" "hello" in the stream, in that order. Then, you stream from that into a string. String spec says that all characters will be copied until the first valid whitespace. It will see "1" as a char, and then stop at the newline. Hence, you will get a string, the string "1";
精彩评论