#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缓冲区有关,但我不知道到底出了什么问题。
答案 0 :(得分:5)
在第
行cin >> startTemperature; // <---problem here
while(!(cin >> startTemperature)){
cin.clear();
cout << "Invalid input. Try again: ";
}
您正在输入一次,然后再循环。这就是你必须两次输入的原因。
只需删除第一个输入行,endTemparature
和stepSize
即可。
答案 1 :(得分:1)
你在while循环之前要求输入,然后在循环条件语句中再次要求输入。将while语句中的条件更改为
while(!cin){
//error handling you already have
cin>>startTemperature; //endTemperature respectively
}
答案 2 :(得分:1)
它不仅适用于温度,而且适用于所有输入。将您的代码更改为以下代码:
cout << "Please enter a start temperature: " << endl;;
while (!(cin >> startTemperature)){
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid input. Try again: ";
}
cout << "Please enter an end temperature: ";
while (!(cin >> endTemperature)) {
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid temperature. Please try again: ";
}
cout << "Please enter a step size: ";
while (!(cin >> stepSize)) {
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid step size. Please try again: ";
}
您有多余的cin
电话。也可以使用std::cin.ignore(std::numeric_limits<int>::max(), '\n');
而不是任意数字256。