我正在从键盘读取文件名并打开指定的文件。然而,决定它是否公开的并不是我的if语句。这是我的代码:
#include "prog.hh"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string fileName;
cout << "Enter the file name to be read: ";
cin >> fileName;
ifstream input_file("fileName");
std::string line_; // string which text file contents will be stored in
if(input_file.is_open()){ // validation to see if the file is open
while(getline(input_file, line_)){
std::cout<<line_<< 'n'; //prints the contents of the file into the console
}
input_file.close();
}
else {
std::cout<<"File is not open"<< 'n';
}
std::cin.get();
编译后,我键入要打开的文件名,然后返回其他消息"file is not open",尽管ifstream应该打开它。我肯定在正确的文件夹中找到了要打开的正确文件。感谢任何帮助,谢谢。
更改
ifstream input_file("fileName");
至
ifstream input_file(fileName);