What does the following code do when the input is 56789 1234 45a72

int i;
float f;
char name[50];

scanf("%2 %f %*d %2s",&i,&f1,&name);

When I ran the code in the compiler and used printf to check the results i got
56 789.000000 45a72
I understand that it didn't 1234 because it was optional and no varaible is declared for it, but for scanning %2s isn't suppose to return the first 2 characters of the string which are 45 I don't understand why it is returning the whole string?

Any help is appreciated

Thanks

Recommended Answers

All 6 Replies

>I understand that it didn't 1234 because it was optional and no varaible is declared for it,
You understand incorrectly, 1234 was skipped because that's what the * is saying when you
inserted it in %*d with the function scanf.


> but for scanning %2s isn't suppose to return the first 2 characters of the string which are 45 I don't understand why it is returning the whole string?
I am surprised that it read something at all. &name is incorrect, that would be the address of the first element of name, i.e. &name[0]

The first %2 I am going to assume is a mistype you did entering the post.
It needs to be %2d

Thank you for your reply.

I changed it &name[0] but it still returns the whole string? Isn't %2s for the first two characters?

Thank you for your reply.

I changed it &name[0] but it still returns the whole string? Isn't %2s for the first two characters?

The %2s does not work because %s means a string regardless of the numbers of characters.
You should use "%2c" instead to achieve what you're trying to do.
Notice also that you can directly use "name" instead of "&name[0]", which is totally equivalent but simpler to write.
Regards,
Pascal.

printf("%c%c",s[0],s[1]);

It will print only first two characters.

The %2s does not work because %s means a string regardless of the numbers of characters.
You should use "%2c" instead to achieve what you're trying to do.

scanf does accept a width field for a string format reading. Therefore scanf( "%2s", two_chars ); would indeed pick only two characters from the stdin, if it doesn't encounter a space nor a newline, and stored in an array of three elements; the two chars and the '\0' terminator.
Most like it, the OP is invoking some undefined behavior ( by giving the wrong parameter ) that over flow beyond the two + 1 chars intended.
My suggestion is:
If you are going to investigate "exotic" behavior, test it by itself.

Nevertheless, using scanf() for reading an string is learning something you need to forget later on.
Use fgets() when you have to read strings.

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.