2017-02-02 36 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