• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 422
  • Last Modified:

Undestanding sscanf

Hello.  I am not that familiar with the C programming language.
What does this do exactly?
route parameter is a character string and offset is an integer initialized to "NOT_SET".
sscanf(route_parameter, "%*s %n", &offset);
0
dpalyca755
Asked:
dpalyca755
  • 2
2 Solutions
 
Justin MathewsCommented:
%n will basically get a count of characters consumed thus far. The preceding "%*s " will skip over the string at the beginning of route_parameter including whitespces (* means just read characters according to conversion spec but don't assign to a variable). It will then assign the characters so far consumed to the variable offset.

For example the following will print 12:

#include <stdio.h>

void main()
{
	int offset;
	char *route_parameter = "asdfa1231   3242 asdf";
	sscanf(route_parameter, "%*s %n", &offset);
	printf("%d\n", offset);
}

Open in new window

0
 
ssnkumarCommented:
> route parameter is a character string and offset is an integer initialized to "NOT_SET".

After executing sscanf(), the value of offset will change.
So, it doesn't matter whether it is initialized to "NOT_SET" or not.
Maybe NOT_SET is a macro, which means 0.

In the statement:
> sscanf(route_parameter, "%*s %n", &offset)
%*s will eat away all the characters upto first space.
%n will keep the count of number of characters eaten by %*s and that will get stored in offset.

So, if the string stroed in route_parameter is "TWO STRINGS",
%*s will read 'T', 'W', 'O' and after this there is a space. So, including space, the number of characters read is 4. So, the offset will get the value 4.
0
 
ozoCommented:
> So, it doesn't matter whether it is initialized to "NOT_SET" or not.
It could matter if the sscanf format fails to match anything, in which case offset would be unchanged.
0
 
ssnkumarCommented:
> > So, it doesn't matter whether it is initialized to "NOT_SET" or not.
> It could matter if the sscanf format fails to match anything, in which case offset would be unchanged.
That is true.
But, in the program that "dpalyca755" is doing, the only thing it is trying to read is a string.
So, the situation you mentioned will arise, only if route_parameter is a null string!
Anyway, you have rightly pointed out the mistake and I agree to your point.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now