0

我的问题很简单,但我似乎找不到合适的解决方案。为了在 C++ 中创建或打开流,您使用以下语法:

ifstream input_data("data.txt")

我希望括号内的内容是用户选择的变量。(我基本上希望用户选择将存储或加载其数据的文本文件的名称)

提前致谢!

4

1 回答 1

1

从问题移动:

在这种情况下, input_data 是一个接受字符串的构造函数,因此您只需在其中放置一个字符串。解决它的一个好方法是:

string a;              // declare the string
cin >> a;              // let the user input the name
a = a + ".txt";        // add the extension
ifstream input_data(a);// run the constructor with the string as an argument. 

注意:在 C++03 中,您需要将字符串转换为 C-String。直到 C++11,fstream 才将字符串作为构造函数的输入。

ifstream input_data(a.c_str()); // Required for C++03
于 2012-12-24T19:02:31.220 回答