C++ 如何根据用户输入打开文件?

C++ 如何根据用户输入打开文件?,c++,filenames,istream,C++,Filenames,Istream,这个代码一直给我错误我不知道我做错了什么? 如何请求用户输入文件名,然后打开该文件并执行以下操作 使用数据的任务 例如: #include <iostream> #include <fstream> #include <string> using namespace std; int main () { ifstream inData; ofstream outData; string fileName; cout << "Enter th

这个代码一直给我错误我不知道我做错了什么? 如何请求用户输入文件名,然后打开该文件并执行以下操作 使用数据的任务

例如:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{ 
ifstream inData;
ofstream outData;
string fileName;

cout << "Enter the data file Name : " << endl;//asks user to input filename
cin >> fileName; //inputs user input into fileName

inData.open(fileName); //heres where i try to open the file with the users input?
outData.open(fileName);
cout << fileName;
return 0;   
} 
#包括
#包括
#包括
使用名称空间std;
int main()
{ 
Iftream inData;
数据流输出;
字符串文件名;
cout fileName;//将用户输入输入文件名
inData.open(fileName);//在这里我尝试使用用户输入打开文件?
outData.open(文件名);

cout您正在将
std::string
对象传递给参数,而不是实际的以null结尾的字符指针。为此,请使用
c_str

inData.open(fileName.c_str());
outData.open(fileName.c_str());

c_str()的意思是什么?@user1725435注意:c++11的这一点已更改。通常,当你说你有错误时,最好将这些错误包括在内。你知道……以防我们的水晶球不在商店维修。对不起,但我认为这是一个简单的问题?可能是(在这种情况下是)但是,将您遇到的错误包括在内始终是一个好主意。谢谢,我下次会这样做:)@user1725435您可以编辑问题以包含所有必要的信息。