【问题标题】:How to open file based on user input? [closed]如何根据用户输入打开文件? [关闭]
【发布时间】:2013-03-26 18:46:37
【问题描述】:

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

例子:

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

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

【问题讨论】:

  • 通常当您说您遇到错误时,最好包含这些错误。你知道……以防我们的水晶球不在店里修理。
  • 抱歉,我认为这是一个简单的问题?
  • 它可能是(在这种情况下 ),但包括您遇到的错误总是一个好主意。
  • 谢谢,下次我会这样做的:)
  • @user1725435 您可以编辑问题以包含所有必要信息。

标签: c++ filenames istream


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 2021-09-06
  • 2020-11-05
  • 1970-01-01
  • 2016-08-29
相关资源
最近更新 更多