[英]Program in c crashes
My code seems to crash everytime i run it, i want to make a program that finds a capital letter in a sentence (str[max]) and it prints out how many times it finds it我的代码每次运行时似乎都会崩溃,我想制作一个程序,在句子中找到大写字母 (str[max]) 并打印出找到它的次数
i get a warning from the build log (warning: 'c' may be used uninitialized in this function) (very entry level programmer here !!)我从构建日志中收到警告(警告:在此函数中可能未初始化使用“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);
} }
You have multiple problems:您有多个问题:
1) Never use gets()
. 1) 永远不要使用
gets()
。 Use fgets()
instead.请改用
fgets()
。
2) You may not always have max
number of characters. 2)您可能并不总是拥有
max
字符数。 So, your condition: for(i=0;i<=max;i++)
is probably wrong.所以,你的条件:
for(i=0;i<=max;i++)
可能是错误的。 Use strlen()
to find out the actual number of chars in str
.使用
strlen()
找出str
的实际字符数。
3) You are reading c
uninitialized here: 3)您正在阅读未初始化的
c
:
str[i] = c;
You probably meant:你可能的意思是:
c = str[j]; /* notice the i -> j change */
4) The argument to isupper()
requires a cast to unsigned char
. 4)
isupper()
) 的参数需要isupper()
为unsigned char
。
5) Initialize i
to 0
in checktimes()
. 5) 在
checktimes()
i
初始化为0
。
In fact, there's a logical error as well.事实上,这也存在逻辑错误。 You would be printing the count of duplicate chars as many times.
您将多次打印重复字符的计数。 If you use an temp array, it can be written as:
如果使用临时数组,则可以写为:
#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.