2014-01-26 122 views
-4

我试图扫描输入,如果用户键入“是”把“等”,否则退出。但是,这不是正确的,当我输入yes时,它表示无效。提前致谢。这短C代码有什么问题

#include <stdio.h> 
char yes='yes'; 
char name[100]; 


int main() 

{ 

    puts("Starting History Project please Enter your name: "); 

    scanf("%s",&name); 

    printf("Hey %s!",name); 

    puts("My name is C! Are you interested about my history? yes or no"); 



    scanf("%s", &yes); 
    if (yes == 'yes') 
    { 
     printf("Starting ADT \n"); 
    } 
    else 
    { 
     printf("Invalid\n"); 
     exit(0); 

    } 

    return(0); 
} 
+1

char yes ='yes'; ???从顶部一个一个地修复。 – herohuyongtao

+0

这是'scanf(“%s”,&name);'和'if(yes =='yes')'... ??错误太多 - 关于 –

+3

未来可能会设置你的编译器警告级别高,并在发布问题之前修复所有警告! – Clifford

回答

2

变量yes是一个char,因此只能保存一个字符或转义序列。比较字符'是'就像比较字母'y'和'是'。 '是'是非法的,它是一个字符串,不能有单引号。您应该使用0 == strcmp(inputStr, "yes")

1

我的编译器推出以下警告,也许你应该修复它们?

foo.c:2:10: warning: multi-character character constant [-Wmultichar] 
char yes='yes'; 
     ^
foo.c:2:10: warning: implicit conversion from 'int' to 'char' changes value from 7955827 to 115 
     [-Wconstant-conversion] 
char yes='yes'; 
    ~~~ ^~~~~ 
foo.c:12:16: warning: format specifies type 'char *' but the argument has type 'char (*)[100]' [-Wformat] 
    scanf("%s",&name); 
      ~~ ^~~~~ 
foo.c:21:16: warning: multi-character character constant [-Wmultichar] 
    if (yes == 'yes') 
      ^
foo.c:21:13: warning: comparison of constant 7955827 with expression of type 'char' is always false 
     [-Wtautological-constant-out-of-range-compare] 
    if (yes == 'yes') 
     ~~~^~~~~~ 
foo.c:28:9: warning: implicitly declaring library function 'exit' with type 'void (int) __attribute__((noreturn))' 
     exit(0); 
     ^
foo.c:28:9: note: please include the header <stdlib.h> or explicitly provide a declaration for 'exit' 
6 warnings generated. 

此外,

  1. ==没有做字符串比较在C
  2. 您还没有分配给yes问题的空间。
0

如果yes要接收字符串,那么您应该将其定义为一个字符串,就像您对name所做的那样。

char yes [32];例如

在测试:

if (yes == 'yes') 

'分隔符是字符常量不是字符串常量 - 你需要"了点。

此外,C中的一个字符串不是第一类数据类型所以您不能简单地测试与==运算符是否相等。相反玩具需要(通过文字或测试字符)的字符串操作库支持:

if(strcmp(yes, "yes")) 

scanf调用本身的标识name已经是一个地址,不需要&并将在事实上导致了不正确的行为。

+0

如果字符串变量yes确实是“yes”,那么您的代码位于if语句的strcmp(yes,“yes”)下面,因为它将评估为0. –

+0

@ChrisZhang :鉴于OP声明“是”,这是真实的,但这是另一个错误。 – Clifford

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

int main(){ 
    char name[100]; 
    char input[16]; 

    puts("Starting History Project please Enter your name: "); 
    scanf("%s", name); 

    printf("Hey %s! ", name); 

    puts("My name is C! Are you interested about my history? yes or no"); 
    scanf(" %s", input); 
    if (!strcmp(input, "yes")){ 
     printf("Starting ADT \n"); 
    } else { 
     printf("Invalid\n"); 
     exit(0); 
    } 

    return 0; 
}