我正在编写一个将温度从摄氏温度转换为华氏温度的代码,反之亦然。到目前为止一切正常,除了一个输出语句无缘无故重复。我不是很有经验(一周前只从Python转到C ++)所以非常感谢所有的帮助。
这是我的代码:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int ConvertCelsius(int C)
{
int F;
F = C *(9 / 5) + 32;
return F;
}
int ConvertFah(int F)
{
int C;
C = (5 * (F - 32)) / 9;
return C;
}
int Conversion(string conv)
{
if (conv == "CF") {
int C;
cout << "Enter Celsius temperature: ";
cin >> C;
int F = ConvertCelsius(C);
cout << "Equivalent Fahrenheit temperature: " << F << endl;
return 0;
}
if (conv == "FC") {
int F;
cout << "Enter Fahrenheit temperature: ";
cin >> F;
int C = ConvertFah(F);
cout << "Equivalent Celsius temperature: " << C << endl;
return 0;
}
else {
cout << "Invalid conversion type." << endl;
return 1;
}
}
int main()
{
int runs;
cout << "How many conversions to be done? ";
cin >> runs;
cout << " " << endl;
for (int i = 1; i <= runs; i++) {
string conv;
getline(cin, conv);
cout << "Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] ";
if (conv != "") {
int check = Conversion(conv);
runs = runs + check;
}
else {
runs = runs + 1;
}
}
return 0;
}
当我运行代码时,我得到以下输出:
How many conversions to be done? 3
Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] CF
Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] Enter Celsius temperature: 12
Equivalent Fahrenheit temperature: 44
Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] FC
Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] Enter Fahrenheit temperature: 56
Equivalent Celsius temperature: 13
Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] CF
Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] Enter Celsius temperature: 67
Equivalent Fahrenheit temperature: 99
Press any key to continue . . .
在这里您可以看到该行&#34;输入转换类型:摄氏度到华氏度[CF]或华氏度到摄氏度[FC]&#34;出现两次。它应该只在用户输入CF或FC之前出现一次。之后,第二行应该只是&#34;输入摄氏温度:&#34;或&#34;输入华氏温度:&#34;。
我试图弄明白自己但到目前为止失败了。任何帮助表示赞赏。感谢。
编辑:我查看了一个建议的解决方案(Why does std::getline() skip input after a formatted extraction?),但是当使用该命令获取两个输入时,它指出了getline()的问题。在我的情况下,我只输入一次输入,但由于某种原因,它输出了for循环和Conversion(conv)函数之外的语句。
答案 0 :(得分:0)
我能够使用user4581301答案解决它。它也在标记的副本中提到。我在main函数中的新for循环如下所示:
for (int i = 1; i <= runs; i++) {
string conv;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //adding this line fixed the problem
cout << "Enter conversion type: Celsius to Fahrenheit [CF] or Fahrenheit to Celsius [FC] ";
getline(cin, conv);
if (conv != "") {
int check = Conversion(conv);
runs = runs + check;
}
else {
runs = runs + 1;
}
}