doubts on scanf("%100[^\n]%*[^\n]", buff);

L

lovecreatesbea...

I've read some post on sent by pete and other experts, and have doubts
on following lines of code.

1.
I think the xstr macro isn't needed, is it safe to just use the str
macro in the following scanf statement instead of xstr?

#define STRINGLENGTH 100
#define str(x) # x
#define xstr(x) str(x)

scanf("%" xstr(STRINGLENGTH) "[^\n]%*[^\n]", string);
getchar();

2.
The following scanf is the equivalent of the above scanf. If the users
input 200 characters at terminal, the chars 101~200 remains in stdin
and the next getchar call just read and discard one char, and there
are 99 characters still remains in stdin. Am I right? Masters, can you
teach me.

scanf("%100[^\n]%*[^\n]", buff);
getchar();
 
E

Eric Sosman

(e-mail address removed) wrote On 03/29/07 12:03,:
I've read some post on sent by pete and other experts, and have doubts
on following lines of code.

1.
I think the xstr macro isn't needed, is it safe to just use the str
macro in the following scanf statement instead of xstr?

#define STRINGLENGTH 100
#define str(x) # x
#define xstr(x) str(x)

scanf("%" xstr(STRINGLENGTH) "[^\n]%*[^\n]", string);
getchar();

No, changing the final xstr to str is not "safe." To
see why, try printing the string to see what it looks like:

puts("%" xstr(STRINGLENGTH) "[^\n]%*[^\n]");

.... and again with the change you think is "safe." See
a difference?
2.
The following scanf is the equivalent of the above scanf. If the users
input 200 characters at terminal, the chars 101~200 remains in stdin
and the next getchar call just read and discard one char, and there
are 99 characters still remains in stdin. Am I right? Masters, can you
teach me.

scanf("%100[^\n]%*[^\n]", buff);
getchar();

You're ignoring the effect of the "%*[^\n]" part.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top