如何在给定位置从动态分配的数组中打印字符串

问题描述 投票:0回答:1

我想使用该函数从keybord打印给定位置的一个字符串,按照它们在数组中的确切顺序,但将其他字符更改为null。问题是函数的第一个循环甚至不会执行,我不知道为什么。

-ex:第一个输出:

e il cie                       enta traspare   e

- 并通过传递给函数a = 2,我想得到如下输出:

cie //and the rest of the chars must be '\0'


char no_words(char *sentence, int a)
{
  int count=0,i,len;
  char lastC;
  len=strlen(sentence);

  if(len > 0)
  {
    lastC = sentence[0];
  }
  for(i=0; i<=len; i++)
  {
    if((sentence[i]==' ' || sentence[i]=='\0') && lastC != ' ')
    {
      count++;
    }
    lastC = sentence[i];

    if(a!=count-1){
      sentence[i] = '\0';
      printf("%c", sentence[i]);
    }else
      printf("%c", sentence[i]);
  }
  return 0;
}

//分隔我的文字的功能

char fun(char *tab, char warunek){

int i,l=0;
l = strlen(tab);
i=0;
char poczatek;


while(i<l){


do{
    if(tab[i] == '\n'){
        printf("\n");
    }

    if(*(tab+i) == warunek && i< l){

        do{

            printf("%c", *(tab+i));
            ++i;

        }while (*(tab+i) != warunek && i < l);
        printf("%c", *(tab+i));

    }

    *(tab+i) = '\0';
    printf("%c", *(tab+i));
    ++i;


}while (*(tab+i) != warunek && i < l);


}
*(tab+l)= '\0';




return 0;

}

//在主要

int main(){

char **array = NULL;
int i,j;
char line[100];  
int line_count=0;
int line_lenght=0;
int a;
char warunek;
int l=0;
int *lenght;
char **arr2 =NULL;

FILE *fp;
fp = fopen("tekst1.txt", "r");
if(fp == NULL){
    printf("blad otwarcia pliku!");
    exit -1;
}

while (fgets(line, sizeof(line),fp) != NULL){ 
    line_count++;
}

rewind(fp);


array = malloc(sizeof(char*) * line_count); 
if (array == NULL){
    return 0;
}


for (i=0; i<line_count; i++){

    fgets(line, sizeof(line), fp); //szczytuje po 1 linii

    line_lenght = strlen(line);


    array[i] = malloc(line_lenght +1); //+1 for null


    strcpy(array[i], line);

}

for (i=0; i<line_count; i++){
    printf("%s", array[i]);
}

printf("\nenter position\n");
scanf(" %d", &a);
printf("\nenter condition\n");
scanf(" %c", &warunek);
printf("\n\n");





for (j=0; j<line_count; j++){

        *(*(array)+j) = fun(*(array+j) , warunek);

}



for (j=0; j<line_count; j++){

    *(*(array)+j)=print_nth_word(*(array+j),a);
    printf("\n");

}



 return 0;

}

c
1个回答
0
投票
void print_nth_word (const char *sentence, int n) {
    int word_no = 0;
    char ch, lch = ' ';

    while (ch = *sentence++) {
        if (ch == ' ' || word_no != n) printf ("%c", '.');
        else printf ("%c", ch);

        if (ch == ' ' && lch != ' ') word_no++;
        lch = ch;
    }
}

我用'\0'替换'.'以使结果可见。

调用:

print_nth_word ("e il cie                       enta traspare   e", i)

输出:

.....cie........................................
© www.soinside.com 2019 - 2024. All rights reserved.