Originally Posted by
Bill Cosby
I want to read a string with scanf
Why scanf? Why not fgets?
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char line[80];
fputs("prompt> ", stdout);
fflush(stdout);
if ( fgets(line, sizeof line, stdin) )
{
static const char delimiters[] = " \n";
int items = 0;
char *ptr = strtok(line, delimiters);
while ( ptr )
{
++items;
printf("ptr = \"%s\"\n", ptr);
ptr = strtok(NULL, delimiters);
}
printf("items = %d\n", items);
}
return 0;
}
/* my output
prompt> one
ptr = "one"
items = 1
prompt> one two
ptr = "one"
ptr = "two"
items = 2
prompt> one two three
ptr = "one"
ptr = "two"
ptr = "three"
items = 3
*/