简体   繁体   中英

Declare a variable and initialize it from a file, all at once

Here is my code:

ifstream f("data.txt");
string dat;
f >> dat;

Is there any way to combine this into one statement, so I could declare and initialize the variable all in one go?

I tried

string dat << f;

But it gave me a syntax error.

The short answer is "no".

The longer answer is, "you can do something that does this, but far from as directly".

 template <typename T>
 T read_from_file(const char *fname)
 {
     T v;
     ifstream f("data.txt");
     f >> v;
     return v;
 }


 ... 

 string dat = read_from_file("data.txt");

However, this doesn't work particularly well if you have anything more than a single data entry [of course, if there is a structure or class with an operator<< declared for the class, it can be used for a structure, but you can't use it, say, to read an array of 10 structs containing the top ten high scores of a game].

And whilst the above is a "clever" little piece of code, the more "natural" code of reading the data after opening the file in a few lines of code will be much clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM