2017-02-02 32 views
-2

我的代碼似乎崩潰每次我運行它,我想要的是找到一個句子一個大寫字母一個程序(STR [MAX]),並打印出有多少次發現它計劃在C崩潰

我從生成日誌警告(警告:「C」這個功能可以用來初始化)(非常入門級的程序員在這裏!)

#include <stdio.h> 
#include <string.h> 
#include "genlib.h" 
#include "simpio.h" 
#include "ctype.h" 


#define max 26 

void checktimes(char str[],char temp); 

int main() 
{ 
char str[max], temp; 
printf("Type a sentence with 25 characters max :"); 
gets(str); 

int i; 
for(i=0;i<=max;i++) 
{ 
temp = str[i]; 
if(isupper(temp)) 
    checktimes(str,temp); 
} 
return 0; 
} 

void checktimes(char str[],char temp) 
{ 
int j,i; 
char c; 
for(j=0; j<=max ; j++) 
{ 
    str[i] = c; 
    if(c == temp) 
     i++; 
} 
printf("%c --> %d",temp,i); 

}

+2

'爲(I = 0; I <= MAX;我++)' - 'i'將從'0'去'max' *包括的*。看到一個問題?那麼,和標準沒有關於'得到'.. –

+0

而你的問題是....? – DevNull

+1

錯誤消息對您的問題非常具體。另外,學會使用調試器(給男人一條魚,.......) – KevinDTimm

回答

1

您有多個問題:

1)千萬不要使用gets()。改爲使用fgets()

2)您可能並不總是有max個字符。所以,你的情況:for(i=0;i<=max;i++)可能是錯誤的。 使用strlen()找出str中的實際字符數。

3)你正在閱讀c未初始化的位置:

str[i] = c; 

你大概的意思是:

c = str[j]; /* notice the i -> j change */ 

4)參數isupper()需要強制轉換爲unsigned char

5)初始化i0,checktimes()


事實上,還有一個邏輯錯誤。您將多次打印重複字符的數量。 如果使用臨時陣列,它可以被寫成:

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

#define max 26 

void checktimes(char str[]); 

int main(void) 
{ 
    char str[max]; 
    printf("Type a sentence with 25 characters max :"); 
    fgets(str, sizeof str, stdin); 
    str[strcspn(str, "\n")] = 0; /* To remove the trailing newline if any. */ 
    checktimes(str); 
    return 0; 
} 

void checktimes(char str[]) 
{ 
    int i = 0; 
    int count[max] = {0}; 
    size_t len = strlen(str); 
    for(i=0; i<len; i++) 
    { 
     if(isupper((unsigned char)str[i])) 
      count[str[i] - 'A']++; 
    } 
    for(i = 0; i < max; i++) 
    if (count[i]) 
     printf("%c --> %d\n",i+'A', count[i]); 
} 
+0

如果'isupper'被定義爲'int isupper(int ch);',爲什麼參數必須被轉換爲'無符號字符? –

+0

@RandomDavis toupper接受一個'int'值,它必須在'unsigned char'中表示。所以,演員有助於避免潛在的未定義行爲。例如,'toupper(-5);'是UB。這一切都詳細的'人toupper'。這同樣適用於ctype.h中的其他函數。 – usr