user4612022
user4612022

Reputation:

C sscanf turn begin of string each time

I've to scan characters in string in order but in that example

char s[8]={"ab"};
char a,b;

sscanf(s,"%c", &a);
sscanf(s,"%c", &b);

printf("%c%c", a, b);

it prints aa. but i need to it prints ab. How can i fix it? Should I print string to file and read from file?

Upvotes: 2

Views: 294

Answers (4)

fjardon
fjardon

Reputation: 7996

It prints aa because this is exactly what you asked for.

How do you expect:

sscanf(s,"%c", &b);

To behave diffently from:

sscanf(s,"%c", &a);

If you want to scan a different portion of the string, you have to pass a different string to sscanf.

if(1 == sscanf(s,"%c", &a))
    sscanf(s+1,"%c", &b);

But honestly, if you need to parse a string char by char just use pointer arithmetic...

Upvotes: 2

xuT
xuT

Reputation: 318

That happens because sscanf reads the first character of the string s in both calls.

Like previous answers said the solution is to use:

sscanf(s,"%c%c", &a, &b);

In this case sscanf will read the first character and assign it to the variable a, then sscanf will continue to read the string and find the next character.

Basically, everytime you call sscanf on a string it will start from the beginning of the string.

Hope it helped you understand why this behaviour is not strange at all.

Upvotes: 0

If you need to read each word char by char and process them, then better way is read the string in loop with termination condition using '\0' check like

while ('\0' != *s)
{
    //process each char
    s++
}

Upvotes: -1

Spikatrix
Spikatrix

Reputation: 20244

Use

sscanf(s,"%c%c", &a, &b);

You can also check the return value of sscanf to make sure that it succeeded in extracting two characters from s. sscanf returns the total number of characters scanned and assigned which in your case would be 2.

An alternative way would be to use

a=s[0]; // Assign first character in `s` to `a`
b=s[1]; // Assign second character in `s` to `b`

Upvotes: 1

Related Questions