tags:

views:

54

answers:

2

what was the syntax to input strings with more than one word i.e with space in between through scanf() not gets()

+1  A: 

Is it

"scanf("%[^\t\n]",string);"

Chubsdad
@subhashis: any chance of accepting this if it met the original intent?
Chubsdad
+1  A: 

I don't think this is possible with scanf(). If you know the number of words you want to read, you can read it with

char str1[100], str2[100];
scanf("%s %s", str1, str2);

Note that this is a huge security loophole, since a user can easily enter a string that's longer than the allocated space.

If you don't know the number of words, you might have to rephrase your question. What do you need to read it for? Why don't you want to use gets(), why does it have to be scanf()?

fat-lobyte
Of course `gets` is its own security loophole too, and one should use `fgets` instead.
Greg Hewgill
there is no a "huge security loophole" if you use the wellknown scanf-formatparameter like "scanf("%99s %99s", str1, str2)"
Thanks gordon, I didn't know about the width field of the formatter. But how will words with > 99 characters be handled? Are the characters correctly discarded, or will they linger on in the input buffer and cause the next formatter to fail?
fat-lobyte
>99 will be handled like strncpy with added '\0'; a field-length in format eats max. field-length chars from input-stream, -> the next formatter eats max. field-length chars from remaining chars and so on