如何将缓冲区中的字符串添加到另一个数组并打印出来?

How to add a string from a buffer to another array and print this?

所以基本上我想写一个词,当我按下回车键时,我想将这个字符串从缓冲区存储到数组。当我写第一个词时它可能会起作用,但是当我想添加第二个词时它变得很棘手。

e.g.1st input is:first[=10=]
    2nd input is:two[=10=]
    then:Ctrl+Z(to get out of the loop)
    Output I want:first two (actually printing the 'array' array.)

我的代码在这里:

position=0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL){
    for (i=position;i<(position+numberOfChars);i++){
        array[i]=buffer[i];
    }
    numberOfChars=strlen(buffer);
    position=position+numberOfChars+1;
}

代码见注释:

position=0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL){

    /* because you want to add space between 'first' and 'two' */ 
    if (position != 0) {
        array[position] = ' ';
        position++;
    }

    /* you need to get the buffer len for THIS iteration */
    numberOfChars=strlen(buffer);

    for (i=position;i<(position+numberOfChars);i++){
        /* i is a valid indice for array but not for buffer[0..numberOfChars-1] */
        /* array[i]=buffer[i]; */
        array[i] = buffer[i-position];
    }

    /* adding one will not add a space char */
    /* position=position+numberOfChars+1; */
    position = position+numberOfChars;
}

/* finaly add the null char at the end of the string (string is null terminated) */
array[position] = '[=10=]';

你也可以试试这个:

printf("Enter a text: \n");

/* set array as an empty string */
array[0] = 0;

/* read from stdin */
while(fgets(buffer, 100, stdin) != NULL) {

    /* append a space to array if it isn't empty */
    if (array[0] != 0) 
        strcat(array, " ");

    /* append buffer to array */
    strcat(array, buffer)
}

/* print resulting array */
printf("%s\n");

请注意,fgets() 还将从标准输入读取的换行符存储到缓冲区中。所以,你想摆脱它。 你想在这两个词之间多加一个space。此外,您初始化 numberOfChars 为时已晚。它应该在复制循环中使用之前发生。

试试这个:

position = 0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL) {
    numberOfChars = strlen(buffer);
    buffer[numberOfChars - 1] = ' '; //this replaces newline with space
    // note that i <= in the condition; to copy the '[=10=]' over
    for (i = position; i <= (position + numberOfChars); i++) {
        array[i] = buffer[i];
    }        
    position = position + numberOfChars;
}