2013-05-19 93 views
0

我编写的这段代码应该读取一个句子和一个字符,检查该字符在该句子中的出现。它在我写代码的时候工作正常,但是当我尝试使用一个函数时它不起作用。我有的问题是声明一个字符串和一个变量字符的函数参数。哪里不对?将字符串和字符传递给函数

#include<stdio.h> 
#include<string.h> 
int occ(char*,char); 
int main() 
{ 
    char c,s[50]; 
    printf("enter a sentece:\n");gets(s); 
    printf("enter a letter: ");scanf("%c",&c); 
    printf("'%c' is repeated %d times in your sentence.\n",c,occ(s,c)); 
} 
int occ(s,c) 
{ 
    int i=0,j=0; 
    while(s[i]!='\0') 
    { 
     if(s[i]==c)j++; 
     i++; 
    } 
    return j; 
} 
+0

除了你从别人那里得到的答案以外,避免使用gets(s);尽可能多地查看此手册页的bug部分以获取更多信息http://linux.die.net/man/3/gets –

回答

4

请注意,你应该得到一个关于occ的声明和它的定义之间的原型不匹配的警告,其中包括编译警告的主机。

当你写:

int occ(s,c) 
{ 

您使用的是预标准或K & [R风格的函数,默认参数类型 - 因为你没有指定任何类型 - 是int。对于char参数没有问题; char *参数不正确。

所以,一切分开,你应该写:

int occ(char *s, char c) 
{ 

与原型一致。

当我编译你的代码,我得到的编译错误:

$ gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -c wn.c 
wn.c:4:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes] 
wn.c: In function ‘main’: 
wn.c:4:5: warning: old-style function definition [-Wold-style-definition] 
wn.c: In function ‘occ’: 
wn.c:11:5: warning: old-style function definition [-Wold-style-definition] 
wn.c:11:5: warning: type of ‘s’ defaults to ‘int’ [enabled by default] 
wn.c:11:5: warning: type of ‘c’ defaults to ‘int’ [enabled by default] 
wn.c:11:5: error: argument ‘s’ doesn’t match prototype 
wn.c:3:5: error: prototype declaration 
wn.c:11:5: error: argument ‘c’ doesn’t match prototype 
wn.c:3:5: error: prototype declaration 
wn.c:14:12: error: subscripted value is neither array nor pointer nor vector 
wn.c:16:13: error: subscripted value is neither array nor pointer nor vector 
wn.c:11:5: warning: parameter ‘s’ set but not used [-Wunused-but-set-parameter] 

注意:它不会花费太多修复代码 - 这编译干净。但是,它确实使用fgets()而不是gets()。你应该忘记gets()现在存在,你的老师应该被解雇提及它的存在。

实施例运行:

$ ./wn 
enter a sentence: amanaplanacanalpanama 
enter a letter: a 
'a' is repeated 10 times in your sentence. 
$ 

代码:

#include <stdio.h> 

int occ(char*, char); 

int main(void) 
{ 
    char c, s[50]; 
    printf("enter a sentence: "); 
    fgets(s, sizeof(s), stdin); 
    printf("enter a letter: "); 
    scanf("%c", &c); 
    printf("'%c' is repeated %d times in your sentence.\n", c, occ(s, c)); 
    return 0; 
} 

int occ(char *s, char c) 
{ 
    int i=0, j=0; 
    while (s[i]!='\0') 
    { 
     if (s[i]==c) 
      j++; 
     i++; 
    } 
    return j; 
} 

的代码应该检查两个fgets()scanf()成功;我得到了懒惰。

+0

谢谢@Jonathan Leffler –

相关问题