2011-10-12 34 views
-1

我正在创建一个菜单,需要从用户的三个输入。Scanf为两个字符串和一个浮点数

char *fullname; 
    char *date; 
    float sal; 
    printf("\nEnter full name: "); 

line92

scanf("%s", &fullname); 
printf("\nEnter hire date: "); 

线94

scanf("%s", &date); 
printf("\nEnter salary: "); 

线96

scanf("%d", &sal); 

这些都是我recieving

错误
Employee.c:92: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’ 
Employee.c:94: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’ 
Employee.c:96: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘float *’ 

我能解释导致这些问题的原因吗?

回答

1

有几个问题:

第一:

当您使用scanf字符串你不使用&。所以只需scanf("%s", fullname);

二:

您的指针不会被初始化。试试这个:

char fullname[256]; 
char date[256]; 

只要你输入最多255个字符,这将工作。

三:

你最后scanf打字不匹配。当您在格式字符串中指定int时,您正在传入float。试试这个:

scanf("%f", &sal); 
+0

这似乎摆脱了警告,但是当你进入它sefaults在我的代码 – jenglee

+0

你可以跟踪哪一行它出现segfaults上? – Mysticial

+0

好吧,我认为它是因为我做错了事而被隔离。我希望能够输入一个全名“John Doe”,但是由于空间的原因它会出现段错误。有没有办法输入这样的字符串 – jenglee

0

的警告是不言自明。当您使用%s格式说明符呼叫scanf时,您需要为其提供一个指向字符串可以复制到的字符数组的第一个元素的指针。你没有这样做,而是给它一个指向char的指针的地址。

char[100] fullname; 
scanf("%s", fullname); 

日期存在相同的问题。另外,请注意,使用上面的代码,如果用户输入长度等于或多于100个字符的字符串,则会发生缓冲区溢出。

如果您使用的是MSVC,您可以使用scanf_s函数来代替,它需要您输入缓冲区的长度。但是,此功能是Microsoft特有的,因此不可移植。

scanf_s("%s", fullname, 100); 

对于薪水,问题是,格式指示符是%d,其用于读取整数,不浮动。使用

scanf("%f", &sal);