简体   繁体   English

一次声明一个变量并从文件中对其进行初始化

[英]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]. 但是,如果您仅拥有一个数据条目,那么这种方法就无法很好地发挥作用[当然,如果存在带有为该类声明了operator<<的结构或类,则可以将其用于结构,但是您可以不能使用它来读取包含游戏前十名最高得分的10个结构的数组]。

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. 尽管上面的代码是“聪明”的小段代码,但是在几行代码中打开文件后读取数据的更“自然”的代码将更加清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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