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

标签 c++ input ifstream

这是我尝试使用的代码:

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

相关文章:

c++ - 如何从数组中删除 2 个连续的重复项? C++

c++ - 在 C++ 中将大型文本文件快速读取为一维结构

android - 强制停止自动旋转(Android、C++、SDL2)

c++ - 不允许在 CMFCRibbonBar 上弹出工具提示

c++ - 以 FLOPS 估算 GPU 的效率(CUDA SAMPLES)

php 解析用户输入

UserControl 中的 WPF InputBinding 在获得焦点之前不起作用

html - 样式化文本输入插入符

c++ - 处理错误的 ifstream

c++ - ifstream 找不到文件?