使用变量存储文件名来读取文件

问题描述 投票:0回答:1

我希望用户能够输入文件名并显示文件中的信息。我使用 ifstream 来读取变量,但它只返回一个错误。我实现了该错误,以便我可以知道程序何时找到该文件。我不知道变量是否需要位于程序的文件夹中。老实说,我不知道如何修改它才能使其工作。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string f_user;
string l_user;

int main(){
   cout<< "What is your first name?";
   cin >> f_user;
   cout<< "What is your last name?";
   cin >> l_user;

   string file_name= f_user + l_user + ".txt";


   ifstream inFile(file_name);

   if(inFile.is_open()){
       string c;
       while (getline(inFile, c)){
           cout<< c;
       }
   }

   if(inFile.fail()){
       cout << "User not Found"<< endl;
   }

   inFile.close();
}
c++ file
1个回答
0
投票

文件可能存在,但

getline
可能会失败。 在这种情况下
fail()
将返回 true。 为了区分这一点,请执行以下操作:

   if(inFile.is_open()){
       string c;
       while (getline(inFile, c)){
           cout<< c;
       }
   } else {
       cout << "User not Found"<< endl;
   }

© www.soinside.com 2019 - 2024. All rights reserved.