如何让 c + + 程序读取用户命名的文本文件

How can I get a c + + program to read in a text file named by the user?

本文关键字:文件 文本 用户 读取 程序      更新时间:2023-10-16

这是我尝试使用的代码:

//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/

当然,如果你没有标题,你需要它们,我认为这只是一个片段。

或者,在"C++11 std::basic_ifstream::open可以接受std::string"(感谢 P0W)