【问题标题】:User inputed file to read from c++用户输入的文件从 C++ 中读取
【发布时间】:2018-02-12 23:40:20
【问题描述】:

我正在尝试使用变量 dnaInput 上的 ifstream 类型从文件中读取。我希望程序能够获取用户输入的内容,然后从他们所说的文件中读取。输入是字符串类型

cout<<"Would you like to continue? (Y/N)"<<endl;
cin>>input;
while(input=='y'||input=='Y')
{
    cout<<"input the name of your file you would like to append to the current bryce.out.txt file."<<endl;
    cout<<"MAKE SURE YOU INCLUDE THE .TXT"<<endl;
    cin>>DNASource;
    dnaInput.open(DNASource.c_str());
    while (dnaInput.fail())
{
    cerr<<"Error opening file!"<<endl;
    cout<<"input the name of your file you would like to append to the current bryce.out.txt file."<<endl;
    cout<<"MAKE SURE YOU INCLUDE THE .TXT (NO SPACES)"<<endl;
    cin>>DNASource;
    dnaInput.open(DNASource.c_str());
}
}

【问题讨论】:

  • 你的问题是什么?这里不清楚。请提供更详细的信息,您究竟想达到什么目标?
  • @Abhijit 我正在尝试获取用户输入的内容,例如“readme.txt”并使用他们的输入打开他们喜欢的文件
  • 好的,打开文件后,您想对该文件做什么?逐行读取文件并打印?
  • 当使用Integrated Development Environment 时,工作目录(运行程序的位置)通常不是您认为的位置。编写一个文件来查看它在哪里结束或getcwd 函数可能会对您有所帮助。所以可能会使用perror 函数来打印错误消息。
  • 您的程序表现如何?是不是找不到文件?你的程序是否一直在打印"Error opening file!"1

标签: c++ string file input


【解决方案1】:

再添加一个字符串变量并修改您的程序,如下所示

 std::string path="/yourpathtothefile/";

 cin>>DNASource;
 path = path + DNASource;
 dnaInput.open(path.c_str());

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2021-03-23
    相关资源
    最近更新 更多