gpt4 book ai didi

c - 如何在 C 中打印字符串数组的特定部分?

转载 作者:行者123 更新时间:2023-11-30 15:45:08 24 4
gpt4 key购买 nike

所以我有一个由空格分隔的单词组成的字符数组。该数组是从输入中读取的。我想打印以元音开头的单词。

我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *insertt (char dest[100], const char sou[10], int poz) {

int cnt=0;

char *fine = (char *) malloc(sizeof(char) * 3);
char *aux = (char *) malloc(sizeof(char) * 3);

strncpy(fine,dest,poz);

strcat(fine,sou);

do {
aux[cnt]=dest[poz];
poz++;
cnt++;
}
while (poz<=strlen(dest));

strcat(fine,aux);
free(aux);

return fine;
}


int check_vowel(char s) {
switch (s) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return 1;
default: return 0;

}
}

int main (void) {

const char spc[]=" ";
char s[100];
char *finale = (char *) malloc(sizeof(char) * 3);
int beg,len,aux; //beg - beginning; len - length;
int i = 0;


printf("s=");
gets(s);


finale = insertt(s,spc,0); //the array will start with a space

do {
if (finale[i]==' ' && check_vowel(finale[i+1])==1) {
beg=i+1; //set start point
do { //calculate length of the word that starts with a vowel
len++;
}
while(finale[len]!=' '); //stop if a space is found
printf("%.*s\n", len, finale + beg); //print the word
}

i++;
}
while (i<=strlen(finale)); //stop if we reached the end of the string

free(finale);
return 0;


}

如果字符是元音,check_vowel函数将返回1,否则返回0。insertt 函数将从指定位置将 const char 插入到 char 中,我用它在数组的开头插入一个空格。

The input: today Ollie was ill
The output: Segmentation fault (core dumped)
Preferred output:
Ollie
ill

我确信问题出在主 do-while 循环中的某个地方,但我只是不知道可能是什么......2 个功能正常工作。谢谢!

最佳答案

您的程序中有很多错误可能会导致 SIGSEGV

1) 函数 insertt 中的 fineaux 指针尚未分配足够的内存。将其更改为:

char *fine = malloc(sizeof(char) * 300);

2) 在外部 do while{} 循环中,条件必须是:

i<strlen(finale)

3) 在内部do while{}中,条件必须是:

while(len<strlen(finale) && finale[len]!=' ');

编辑:

您的代码中仍然存在一个逻辑错误,我将其留给您来解决:

对于字符串:

adfajf isafdadsf ifsfd

您的输出是:

adfajf 
isafdadsf ifsfd
ifsfd

这是错误的!!

关于c - 如何在 C 中打印字符串数组的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19208019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com