-2

Is there a way where I can initialize an empty string array and then later ask for an input from user which is saved into the string array leaving the empty leading spaces if the input is smaller. I am planning on using a longer string array with addition spaces so that I can do inplace character replacements . for example :

char foo[25];
scanf(%s,foo);
foo = this is a test"
print foo; 

Result be like :

"this is a test      "
Fenomatik
  • 457
  • 2
  • 8
  • 22

1 Answers1

0

Your question is inconsistent, you ask about leading whitespace but your example shows trailing whitespace. If you mean trailing whitespace, you could do it this way:

#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 25

int main() {

    char string[BUFFER_SIZE];
    memset(string, ' ', BUFFER_SIZE - 1); // initialize with spaces
    string[BUFFER_SIZE - 1] = '\0'; // terminate properly

    if (fgets(string, BUFFER_SIZE, stdin) != NULL) {

        size_t length = strlen(string);

        string[length - 1] = ' '; // replace the newline \n

        if (length < BUFFER_SIZE - 1) {
            string[length] = ' ';  // replace extra '\0' as needed
        }

        printf("'%s'\n", string); // extra single quotes to visualize length
    }

    return 0;
}

USAGE

> ./a.out
this is a test
'this is a test          '
> 

The single quote were only added so you could actually see the spaces were preserved. The approach of @BLUEPIXY makes perfect sense except that it appends new whitespace to the input where you specifically asked about preserving existing whitespace.

If instead you want to preserve leading whitespace, that can probably be done as well.

cdlane
  • 40,441
  • 5
  • 32
  • 81