c++ - Bjarne Stroustrup 第 10.5 章示例

标签 c++ iostream

这是关于 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;
}

最佳答案

当你看到提示时:

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”的 vector 中

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

关于c++ - Bjarne Stroustrup 第 10.5 章示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31037222/

相关文章:

c++ - 无法使用 LoadIcon() 在 Visual C++ 中设置正确的托盘图标

C++ 在 cin 时忽略特定字符

c++ - 如何使用同一个函数C++实例化多个线程

c++ - 将什么传递给 H.264 传输流的 avcodec_decode_video2?

c++ - Microsoft SAL 如何防止差一错误

c++ - 我无法理解 C++ 中的 char[] 行为

c - 扫描文件时C中的无限循环

c++ - 在类中重载 << 运算符

c++ - 如何使用 cout 打印 0x0a 而不是 0xa?

c++ - 将代码块中的所有输出流式传输到 C++ 中的文本文件