簡體   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