使用 getchar 比较 C 中的字符串

标签 c string char comparison buffer

我知道之前有人问过这个问题,我已经通读了答案。我也知道我的代码不是很好,因为我还在学习 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/

相关文章:

c - Valgrind 在二维数组中读取 1 的大小无效

python - Ruby 字符串翻译

c++ - 硬币翻转计数游戏 C++ 数据结构!

c - 如何在c中创建自定义数据包?

c - 从文件中读取日语字符的问题 - C

C:字符到位并打印

string - Bash:用空字符串替换子字符串

java - 使用Java和正则表达式来修复路径

java - 在位置 x 处将 char 添加到字符串中

C++如何将大字符串放入固定字符数组中