繁体   English   中英

c 中的程序崩溃

[英]Program in c crashes

我的代码每次运行时似乎都会崩溃,我想制作一个程序,在句子中找到大写字母 (str[max]) 并打印出找到它的次数

我从构建日志中收到警告(警告:在此函数中可能未初始化使用“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);

}

您有多个问题:

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() ) 的参数需要isupper()unsigned char

5) 在checktimes() i初始化为0


事实上,这也存在逻辑错误。 您将多次打印重复字符的计数。 如果使用临时数组,则可以写为:

#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]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM