0

How can i Store strings which are inputted using spaces. For eg: Strings entered using newline can be stored using for loop and then stored to array, Similarly how to store strings which are entered as a single line, but with spaces

Tom J Muthirenthi
  • 3,028
  • 7
  • 40
  • 60

1 Answers1

1

Use fscanf's %s format directive. It has a field width if you're interested in avoiding buffer overflows (which you should be), for example char foo[128]; int x = fscanf(stdin, "%127s", foo);... Don't forget to check x.

There's some error checking that needs to occur after reading such a fixed width field. If fscanf reads the maximum number of characters, it's required to stop reading... There's a good chance that some non-space characters might be left on the stream, which should be discarded using something like: fscanf(stdin, "%*[^ \n]");. You might also want to let the user know that their input has been truncated.

Alternatively, if you'd like to read really large words of an unknown length you could use this function I wrote:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

char *get_dynamic_word(FILE *f) {
    size_t bytes_read = 0;
    char *bytes = NULL;
    int c;
    do {
        c = fgetc(f);
    } while (c >= 0 && isspace(c));
    do {
        if ((bytes_read & (bytes_read + 1)) == 0) {
            void *temp = realloc(bytes, bytes_read * 2 + 1);
            if (temp == NULL) {
                free(bytes);
                return NULL;
            }
            bytes = temp;
        }

        bytes[bytes_read] = c >= 0 && !isspace(c)
                          ? c
                          : '\0';
        c = fgetc(f);
    } while (bytes[bytes_read++]);
    if (c >= 0) {
        ungetc(c, f);
    }
    return bytes;
}

Example: char *foo = get_dynamic_word(stdin); Don't forget to free(foo);...

An example assigning words to an array? No problemo:

char *bar[42] = { 0 }
bar[0] = get_dynamic_word(stdin);
bar[1] = get_dynamic_word(stdin);
/* ... */

Don't forget to free(bar[0]); free(bar[1]); /* ... */

autistic
  • 1
  • 3
  • 35
  • 80