2017-06-27 69 views
1

我有这个应该是'聊天模拟器'的程序,它现在唯一要做的就是回复'你好!'当用户输入'Hello'时。有没有可能的方式来在strcmp中使用char?

#include <stdio.h> 
#include <stdlib.h> 
#include <windows.h> 
#include <string.h> 

int main() 
{ 
    printf("Chat simulator!\n"); 
    do { 
     char x; 
     printf("[User1] "); 
     scanf("%s",&x); 
     if (strcmp (x,"Hello") == 0) 
     { 
     Sleep(1500); 
     printf("[User2] Hello!\n"); 
     } 
     else {} 
    } while(1); 
} 

我知道strcmp仅供const char *,不是一个单一的char,这里这就是问题所在,但我无法找到任何相关的解决方案,因为我需要在scanf使用char x,所以它不能是const char *
也有可能我使用的是strcmp错误。
代码:块警告:

passing argument 1 of 'strcmp' makes pointer from integer without a cast* 
expected 'const char *' but argument is of type 'char'* 

编辑:

所以我改变了char到​​为@ robin.koch告诉我,一切正常,因为它应该。谢谢!

+0

为什么你尝试将用户的信息(整个报文)存储'char'里面? –

+4

问题不在于你认为的地方。 'x'是一个单独的'char',而你试图将一个字符串(字符数组)填入它。 –

+0

x只有一个字符。您正试图存储一个字符串(多个字符)。改用char数组。 char x [16];例如。 –

回答

0

正如其他人指出的那样,当字符仅用于存储一个字符时,您试图使用scanf将字符串存储到char变量中。您应该使用char *char[]变量来代替您的字符串。因此,改变

char x; 
printf("[User1] "); 
scanf("%s",&x); 
//...rest of your code... 

char * x = malloc(sizeof(char) * 10); //can hold up to ten characters 
printf("[User1] "); 
scanf("%s",x); 
//...rest of your code... 
free(x); 

请注意,如果你只是想用一个字符数组,而不是一个指针,你可以用一些替代上面第一行像char x[10];,摆脱free(x);

4

你不能比较一个字符串与charstrcmp,但它很容易做手工:

int samechar(const char *str, char c) { 
    return *str == c && (c == '\0' || str[1] == '\0'); 
} 

上述功能然而,这不是你需要什么,你的问题:

  • 你应该从用户,而不是单个字符阅读的字符串。
  • scanf()需要一个指向char数组的指针,用于转换说明符%s
  • 此外,您应该指定要存储到此数组中的最大字符数,以避免潜在的缓冲区溢出。
  • 最后,scanf()只会读取一个单词。您可能想要阅读用户的全部内容。为此,请使用fgets()

下面是修改后的版本:

#include <stdio.h> 
#include <string.h> 

int main(void) { 
    printf("Chat simulator!\n"); 
    for (;;) { 
     char buf[100]; 
     printf("[User1] "); 
     if (!fgets(buf, sizeof buf, stdin)) 
      break; 
     buf[strcspn(buf, "\n")] = '\0'; /* strip the newline if present */ 
     if (strcmp(buf, "Hello") == 0) { 
      printf("[User2] Hello!\n"); 
     } 
    } 
    return 0; 
} 
+0

覆盖'c =='\ 0''的简单情况:'return * str == c &&(c =='\ 0'|| str [1] =='\ 0');' – alk

相关问题