【问题标题】:How can I get a c + + program to read in a text file named by the user?如何让 c++ 程序读取用户命名的文本文件?
【发布时间】:2013-11-12 02:24:58
【问题描述】:

这是我尝试使用的代码:

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

文本文件只是人员姓名和工资率的列表。代码不会按原样编译,我不知道为什么它不会将字符串读取为文本文件名。

【问题讨论】:

  • 你遇到了什么错误?
  • 如果这是整个代码,那么您缺少包含几个标题,您需要一个 main 函数。
  • 总是发布编译器错误,所以我们不需要猜测。
  • 这是你的代码,还是你也在某个地方找到的?
  • “代码不会编译”不是问题描述。错误信息(和消息)就在您的屏幕上(我们无法从这里看到)。绝对没有任何借口不将其包含在您的帖子中。请edit 这样做。如果您希望我们为您提供帮助,您需要提供我们可以使用的信息

标签: c++ input ifstream


【解决方案1】:
cout << "Enter filename: ";
std::string filename;
cin >> filename;
cout << endl;

// Open file
ifstream file(filename.c_str());

这不是我的代码,但它会做你想做的事。 来源:http://www.cplusplus.com/forum/beginner/1007/

当然,如果你没有标题,你需要它们,不过我认为这只是一个 sn-p。

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

【讨论】:

  • 既然C++11std::basic_ifstream::open可以接受std::string
  • 要明确一点:@MarJamRob 将 std::string 转换为 const char *,这是 std::ifstream 函数的可接受类型。
猜你喜欢
  • 2018-05-03
  • 2013-04-21
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
相关资源
最近更新 更多