specifier "%n" when using "scanf"

T

thomas

Hi,
I used to see a format specifier "%s%n" for "scanf", like
follows.

------------code---------
#include<iostream>
using namespace std;

int main(){
char xx[20];
strcpy(xx, "ab ad ef");
char yy[20]; int jj;
cout<<sscanf(xx, "%s%n", yy, &jj)<<endl;
cout<<yy<<" "<<jj<<endl;
}
--------code-----------

But I didn't find any explaination about the "%n" usage in the web or
text books.
Can anyone give some references?
 
M

Maxim Yegorushkin

thomas said:
Hi,
I used to see a format specifier "%s%n" for "scanf", like
follows.

------------code---------
#include<iostream>
using namespace std;

int main(){
char xx[20];
strcpy(xx, "ab ad ef");
char yy[20]; int jj;
cout<<sscanf(xx, "%s%n", yy, &jj)<<endl;
cout<<yy<<" "<<jj<<endl;
}
--------code-----------

But I didn't find any explaination about the "%n" usage in the web or
text books.

It returns the number of bytes consumed by sscanf by that point, provided it
gets to that point.
Can anyone give some references?

http://www.opengroup.org/onlinepubs/009695399/functions/scanf.html
 
A

Alexander Bartolich

thomas said:
Hi,
I used to see a format specifier "%s%n" for "scanf", like
follows.

C++1998 is based on C90, so technically scanf is part of C++.
Nevertheless the function is described by the C standard and
is rarely mentioned in literature about C++.
[...]
But I didn't find any explaination about the "%n" usage in the
web or text books.

Hard to believe.
Can anyone give some references?

http://man-wiki.net/index.php/3:fscanf
# n Nothing is expected; instead, the number of characters consumed
# thus far from the input is stored through the next pointer, which
# must be a pointer to int. This is not a conversion, although it can
# be suppressed with the * assignment-suppression character. The C
# standard says: "Execution of a %n directive does not increment the
# assignment count returned at the completion of execution" but the
# Corrigendum seems to contradict this. Probably it is wise not to make
# any assumptions on the effect of %n conversions on the return value.

http://msdn.microsoft.com/en-us/library/6ttkkkhh(VS.71).aspx
# n No input read from stream or buffer.
# Pointer to int, into which is stored number of characters successfully
# read from stream or buffer up to that point in current call to scanf
# functions or wscanf functions.
 

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