Search code examples
c++cloopsbufferfgets

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


So basically I want to write a word, and when I press enter I want to store this string from buffer to array. As I write the first word it might work but when I want to add a second word it is getting tricky.

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

My Code is Here:

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;
}

Solution

  • See comments in the code:

    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] = '\0';
    

    You may also try this:

    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");