我正在尝试在摄氏度和华氏度之间制作一个转换器,但我有一个问题。当我运行我的代码端输入"摄氏度到华氏度"时,它被终止。这是我的代码:
#include <iostream>
int main() {
std::string ftc;
int f;
int c;
std::cout << "Celsius to Fahrenheit or Fahrenheit to Celcius ";
std::cin >> ftc;
if(ftc == "Celsius to Fahrenheit") {
std::cout << "(c to f) Please provide input ";
std::cin >> c;
f = (c*1.8)+32;
std::cout << f;
} else if(ftc == "Fahrenheit to Celsius") {
std::cout << "(f to c) Please provide input ";
std::cin >> f;
c = (f-32)*0.5556;
std::cout << c;
}
}
cin
在遇到空格时将停止读入ftc
,因此它只会读取一个单词。请改用std::getline()
。这应该有效:
#include <iostream>
#include <string>
int main() {
std::string ftc;
int f;
int c;
std::cout << "Celsius to Fahrenheit or Fahrenheit to Celcius ";
std::getline(std::cin, ftc);
if(ftc == "Celsius to Fahrenheit") {
std::cout << "(c to f) Please provide input ";
std::cin >> c;
f = (c*1.8)+32;
std::cout << f;
} else if(ftc == "Fahrenheit to Celsius") {
std::cout << "(f to c) Please provide input ";
std::cin >> f;
c = (f-32)*0.5556;
std::cout << c;
}
}
阅读此内容以获取更多信息:http://www.cplusplus.com/doc/tutorial/basic_io/
问题出在
if(ftc == "摄氏度到华氏度"( 尝试使用单个单词,例如
if(ftc == "摄氏度"(
有效!这样