【问题标题】:Bjarne Stroustrup chapter 10.5 exampleBjarne Stroustrup 第 10.5 章示例
【发布时间】:2015-06-24 21:17:30
【问题描述】:

这是关于 Bjarne Stroustrup 的“使用 C++ 的原则和实践”一书第 10.5 节中的一个示例。据我了解,它应该提示用户输入要创建的文件的名称(所以我输入了probe.txt),然后它应该要求用户打开一个文件(所以我再次输入probe.txt)然后程序跳过我的while 语句并返回0。我应该如何输入小时和温度?

#include <std_lib_facilities.h>

struct Reading {
    int hour;
    double temperature;
};

int main()
{
    cout << "Please enter input file name: \n";
    string iname;
    cin >> iname;
    ifstream ist{iname};

    string oname;
    cout << "Please enter output file name: \n";
    cin >> oname;
    ofstream ost{oname};

    vector<Reading> temps;
    int hour;
    double temperature;
    while (ist >> hour >> temperature) {
        temps.push_back(Reading{hour,temperature});
    }

    keep_window_open();
    return 0;
}

【问题讨论】:

  • 您必须事先创建文件(例如使用记事本)并在此处输入数据。并且不要写入您正在读取的文件。
  • 您不输入时间和小时,它会从文件中读取它们。
  • 啊,所以在这个例子中它只是将文件中的数据写入一个名为 temps 的向量中。所以如果我想打印出数据,我必须从向量中打印出来?
  • 这是正确的,它只是处理文件,如果你想打印你将不得不改变例子。

标签: c++ iostream


【解决方案1】:

当你看到提示时:

cout << "Please enter input file name: \n";

它询问您要从哪个文件读取数据。

当你看到提示时:

cout << "Please enter output file name: \n";

它询问你要写入哪个文件。

注意关键字inputoutput的区别。

这个循环:

while (ist >> hour >> temperature) {
            temps.push_back(Reading{hour,temperature});

是说虽然 ist(输入文件流)返回了一个好的值(意味着它还没有到达文件的末尾),但我们向 Vector 添加了一个名为“temps”的 Reading 类型的项目。 (Vector 本质上是一个列表容器类型)我们从文件中的行中抓取的两个项目中创建了一个 Reading 类型的项目。

回顾一下,我们从文件中的文本中读取,然后将其添加到名为“temps”的向量中

">>" 是读取文件中下一项的运算符。 在代码中,它读取接下来的两项并将它们放入小时和温度中。

【讨论】:

  • 非常感谢您的详细解释。看起来我实际上期待该程序的不同行为。 :) 现在没有意义了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2014-03-18
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多