这是我尝试使用的代码:
//Have the user input the file name that they want to read
cout << "Enter name of file: ";
cin >> recordName;
//Create the object that the file will be read into
ifstream records;
//Open file for reading
records.open(recordName);
文本文件只是人员姓名和工资率的列表。代码不会按原样编译,我不知道为什么它不会读取字符串作为文本文件名。
最佳答案
cout << "Enter filename: ";
std::string filename;
cin >> filename;
cout << endl;
// Open file
ifstream file(filename.c_str());
这不是我的代码,但它会做你想做的。 来源:http://www.cplusplus.com/forum/beginner/1007/
当然,如果没有 header ,则需要 header ,不过我认为这只是一个片段。
或者,在“C++11 std::basic_ifstream::open
中可以接受 std::string
”(感谢 P0W)
关于c++ - 如何让 C++ 程序读取用户命名的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919765/