我想使用该函数从键盘上打印出给定位置的一个字符串,并按照它们在数组中的确切顺序将其他字符更改为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;
}
答案 0 :(得分: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........................................