2013-05-19 155 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 –

相關問題