今天尝试想把用户输入的文件名,然后打开,可是一直是打不开的txt,求指导本人代码错了吗?代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* Function prototypes */
string promptUserForFile(ifstream & infile, string prompt = "");
/* Main program */
int main() {
ifstream infile;
promptUserForFile(infile, "Input file: ");
while (true) {
int ch = infile.get();
if (ch == EOF) break;
cout.put(ch);
}
infile.close();
return 0;
}
string promptUserForFile(ifstream & infile, string prompt) {
while (true) {
cout << prompt;
string filename;
getline(cin, filename);
infile.open(filename.c_str());
if (!infile.fail()) return filename;
infile.clear();
cout << "Unable to open that file. Try again." << endl;
if (prompt == "") prompt = "Input file: ";
}
}
但是运行时候找不到文件:
解决方案
10
默认路径是工程目录下的路径
假如是其他地方请使用相对路径或绝对路径
假如是其他地方请使用相对路径或绝对路径
20
输入完整路径,或把那个txt文件放到程序目录下