Bjarne Stroustrup第10.5章示例

Bjarne Stroustrup chapter 10.5 example

本文关键字:5章 Stroustrup Bjarne      更新时间:2023-10-16

这是关于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添加一个类型为Reading的项,称为"temps"。(Vector本质上是一个列表容器类型)我们从文件中的行中抓取的两个项目中创建了一个Reading类型的项目。

概括一下,我们从文件中的文本中读取,然后将其添加到名为"temps"的向量中

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