c++ - 必须输入两次值才能工作 C++

标签 c++

#include <iostream>
#include <limits>
#include <math.h>

using namespace std;

int main()
{
    float startTemperature;
    float endTemperature;
    float loopTemperature;
    float stepSize;
    float i;
    float numberOne;
    cout << "Please enter a start temperature: " << endl;;
    cin >> startTemperature;
    while(!(cin >> startTemperature)){
        cin.clear();

        cout << "Invalid input.  Try again: ";
    }
    cout << "Please enter an end temperature: ";
    cin >> endTemperature;
    while(!(cin >> endTemperature)) {
        cin.clear();
        cin.ignore(256, '\n');
        cout << "Invalid temperature. Please try again: ";
    }
    cout << "Please enter a step size: ";
    cin >> stepSize;
    while(!(cin >> stepSize)) {
        cin.clear();
        cin.ignore(256, '\n');
    }
    for(i = startTemperature; i < endTemperature; i += stepSize) {
        if(i == startTemperature) {
            cout << "Celsius" << endl;
            cout << "-------" << endl;
            cout << startTemperature << endl;
            loopTemperature = startTemperature + stepSize;
        }
        loopTemperature += stepSize;
        if(loopTemperature > 20) {
            break;
        }
        cout << loopTemperature << endl;
    }
}

您好,此代码的问题是我必须输入两次温度值。我看过其他答案,我认为这与 cin 缓冲区有关,但我不知道到底出了什么问题。

最佳答案

行内

cin >> startTemperature;  // <---problem here
while(!(cin >> startTemperature)){
    cin.clear();

    cout << "Invalid input.  Try again: ";
}

您正在输入一次,然后在循环中再次输入。这就是为什么您必须输入两次。

只需删除第一行输入,endTemparaturestepSize 也是如此。

关于c++ - 必须输入两次值才能工作 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23958008/

相关文章:

c++ - 如何使用 C++ 访问文本文件中的特定值

c++ - 什么是适合 opengl 常量的类型名称?

c++ - std::bind 带有可变函数参数,包括带有可变参数的回调函数

c++ - 是否在扩展宏之前处理预处理器指令?

c++ - 命名空间问题

c++ - 从 vector c++ 中获取匹配项的索引

c++ - 如何通过以太网套接字从摄像机捕获视频

c++ - 在没有函数指针/内联的情况下将 C++ 函数作为参数传递?

c++ - STL BigInt 类实现

c++ - 从模板化函数返回字符串时,bad_any_cast异常