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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15645025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:35:01  来源:igfitidea点击:

How to open file based on user input?

c++filenamesistream

提问by user1725435

This code keeps giving me errors i dont know what Im doing wrong? How can I request the user to input the filename and then open that file and perform tasks with the data.

这段代码不断给我错误,我不知道我做错了什么?如何请求用户输入文件名,然后打开该文件并使用数据执行任务。

Example:

例子:

#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;   
} 

The code keeps giving me errors. I have tried to use getline? I want the fileName to be string and not char.

代码不断给我错误。我试过用getline吗?我希望文件名是字符串而不是字符。

回答by 0x499602D2

You're passing std::stringobjects to the parameters, not actual null-terminated char pointers. To do that, use c_str:

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

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