c++ - std::cout不输出任何内容

标签 c++

我正在阅读Stroustrup的书《使用C++编程原理和实践》。我可以输入温度,但是在控制台中却没有std::cout。我没有编译错误。
这是代码。


#include <iostream>
#include <vector> // I added this which is different from the book

void push_back(std::vector<double> temps, double value) { // I added this which is different from the book, maybe I don't need this but I found it doing a search
    temps.push_back(value);
}

int main() {
    std::vector<double> temps;

    double temp = 0;
    double sum = 0;
    double high_temp = 0;
    double low_temp = 0;

    std::cout << "Please enter some integers"<< '\n';  // I added this in for the prompt

    while (std::cin >> temp)
        temps.push_back(temp);

    for (int i = 0; i < temps.size(); ++i) {
        if (temps[i] > high_temp) high_temp = temps[i];
        if (temps[i] < low_temp) low_temp = temps[i];
        sum += temps[i];
    }
        std::cout << "High temperature: " << high_temp << std::endl;  // There is no output for this and the next two lines
        std::cout << "Low temperature: " << low_temp << std::endl;
        std::cout << "Average temperature: " << sum/temps.size() << std::endl;

    return 0;
}


最佳答案

您的代码的问题在于,它不断循环等待输入。
我稍作更改,询问要输入多少个值,以便您检查输出是否确实有效。

#include <iostream>
#include <vector> // I added this which is different from the book

void push_back(std::vector<double> temps, double value) { // I added this which is different from the book, maybe I don't need this but I found it doing a search
    temps.push_back(value);
}

int main() {
    std::vector<double> temps;

    double temp = 0;
    double sum = 0;
    double high_temp = 0;
    double low_temp = 0;
    int ntemp;

    std::cout << "Enter the number of temperatures to input:";
    std::cin >> ntemp;

    std::cout << "Please enter " << ntemp << " doubles"<< '\n';  

    for (int i = 0; i < ntemp; ++i)
    { 
        std::cin >> temp;
        temps.push_back(temp);
    }

    for (int i = 0; i < temps.size(); ++i) {
        if (temps[i] > high_temp) high_temp = temps[i];
        if (temps[i] < low_temp) low_temp = temps[i];
        sum += temps[i];
    }
        std::cout << "High temperature: " << high_temp << std::endl;  // There is no output for this and the next two lines
        std::cout << "Low temperature: " << low_temp << std::endl;
        std::cout << "Average temperature: " << sum/temps.size() << std::endl;

    return 0;
}

关于c++ - std::cout不输出任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65022403/

相关文章:

C++调试: Terminated with SIGABRT

c++ - 这个算法的复杂度是多少

C++ 使用 std::string, std::wstring 作为缓冲区

C++ 在删除前复制 vector 范围

c++ - 为什么 operator""隐藏在命名空间中?

C++ : problem when trying to create an instance

c++ - 如何让构造函数接受所有类型的迭代器?

c++ - Unix Domain Sockets, Udp Sockets Objective C 有什么用?

c++ - C++ 风格转换对性能的影响?

c++ - unordered_map 找不到 key