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
-
3You can use functions fgets and strtok. – Vlad from Moscow Jul 04 '15 at 07:34
-
`scanf("%s", str)` in a loop? – Spikatrix Jul 04 '15 at 07:35
-
After entering I want to store each word into an array. – Tom J Muthirenthi Jul 04 '15 at 07:52
-
1I'm voting to close this question as off-topic because you don't need help if you already know what you're doing (e.g. you think `stdin` isn't the console, or isn't a `FILE *`, and thus anything that operates on `FILE *` won't help you)... right? – autistic Jul 04 '15 at 08:12
1 Answers
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]); /* ... */

- 1
- 3
- 35
- 80