int getter2(char str[])
{
int len=0;
scanf("%100[^\n]s",str);
while (str[len++] != '\0');
return len-1;
}
int wordmaker(char str[],char word[15][15],int len)
{
int i,temp=0,j=0;
for (i=0;i<len;i++){
if (((str[i]>='a') && (str[i]<='z')) || ((str[i]>='A') && (str[i]<='Z'))){
word[j][temp++] = str[i];
}
else{
j++;
temp=0;
}
}
for (i=0;i<15;i++)
for (j=0;j<15;j++)
printf("%c",word[i][j]);
}
int main()
{
char line[max],word[15][15];
int len;
printf("%d\n%s\n",getter2(line),line);
wordmaker(line,word,len);
}
core dumped.segmentation fault.wordmaker功能有问题。我没有结束。当我运行程序时,我得到了正确放置的句子以及适当的长度。字库制作功能似乎是问题所在。 有人可以帮我调试吗。
答案 0 :(得分:1)
我修复了代码中的一些问题并使其正常工作。但是有一个问题:如果你没有输入15个单词,它将打印垃圾(因为for (i = 0; i < 15; i++)
中的wordmaker
循环)。
一般要点:
s
的格式字符串中不需要scanf()
。 wordmaker
的返回类型应为void
。getter2
内分配了len
到main
的返回值。代码中的所有内容:
/* str.c
* gcc -o str str.c -Wall
*/
#include <stdio.h>
/* As pointed by @BLUEPIXY, this should be 101 because of the format
* string of scanf. It will read 100 characters from stdin into the
* string, but it doesn't take into account the terminating NULL byte.
*/
#define max 101
int getter2(char str[])
{
int len = 0;
/* no need the trailing s in format string */
scanf("%100[^\n]", str);
while (str[len++] != '\0');
return len - 1;
}
/* changed return type to void, since you're not returning anything */
void wordmaker(char str[], char word[15][15], int len)
{
int i, temp = 0, j = 0;
for (i = 0; i < len; i++) {
if (((str[i] >= 'a') && (str[i] <= 'z'))
|| ((str[i] >= 'A') && (str[i] <= 'Z'))) {
word[j][temp++] = str[i];
} else {
/* put the terminating null byte on each string */
word[j][temp] = 0x0;
j++;
temp = 0;
}
}
/* print the strings, not their characters
*
* If you use a loop to print characters, you need to have 15 byte
* strings, otherwise you're gonna print garbage.
*/
for (i = 0; i < 15; i++)
printf("%s\n", word[i]);
}
int main()
{
char line[max], word[15][15];
int len;
/* here a little modification to initialize the variable 'len' */
printf("%d\n%s\n", (len = getter2(line)), line);
wordmaker(line, word, len);
}
作为旁注,如果您添加ctype.h
,则可以更改((str[i] >= 'a') && (str[i] <= 'z')) || ((str[i] >= 'A') && (str[i] <= 'Z'))
isalpha(str[i])
,这更清晰。 isalpha() manual。