所以我有一个由空格分隔的单词组成的字符数组。 从输入读取数组。我想打印以元音开头的单词。如何在C中打印字符串数组的特定部分?
我的代码:
#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成焦炭从一个指定的位置,我用它在数组的开头插入一个空格。
The input: today Ollie was ill
The output: Segmentation fault (core dumped)
Preferred output:
Ollie
ill
我敢肯定,问题是在主要do-while循环的地方,但我只是想不出什么可能是它... 的2个功能正常工作。 谢谢!
正如我所说,2个功能(insertt和检查元音)正常工作,他们做的正是它们是什么应该这样做:) –
将输入读入字符串数组不是更容易吗? – LihO
适合我:jrenner @ pc:〜$。/ test s =今天Ollie生病了 Ollie ill – talloaktrees