我知道之前有人问过这个问题,我已经通读了答案。我也知道我的代码不是很好,因为我还在学习 C。我正在尝试比较用户输入的 char 和 if 语句中的 char,但运气不佳。所有和任何建议表示赞赏。此外,我知道缓冲区问题,尽管我只是想先进行比较。
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void){
//int n;
//const char *F = "F";
//float temp;
//float converted;
printf("Would you like to enter Fahrenheit or Celcius? Please type F or C: ");
//scanf("%c", &a);
char input = getchar(); //This will get a single Char from the user and keep it as a char
printf("%c\n", input);
//n = strcmp(input, F);
if(input == "C") {
printf("Please enter the temp you would like to convert to Fahrenheit: ");
scanf("%f", &temp);
converted = temp * 9/5 +32;
printf("You entered %2f Celcius and that equals %2f Fahrenheit\n", temp, converted);
}else if(strcmp(input, "f") == 0) || (strcmp(input, "F") == 0){
printf("Please enter the temp you would like to convert to Celcius: ");
scanf("%f", &temp);
}else{
printf("You didn't enter F or C");
}
}
最佳答案
int strcmp ( const char * str1, const char * str2 );
strcmp
接受两个 string
变量。
但是您的input
变量是char
。所以使用 if(input == 'C')
和 if(input == 'F')
关于使用 getchar 比较 C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468216/