Click here to Skip to main content
15,888,003 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
#include<stdio.h>
main()
{
 char name[15],age[3];
 printf("Please enter your name :\n");
 scanf("%[^$]",&name);
 printf("Your name is %s.\n",name);
 printf("Please enter your age :\n");
 scanf("%s",&age);
 printf("Your age is %s\n",age);
 getch();
}


Input :
Shubham$$
Output :
Your name is Shubham.
Please enter your age :
Your age is $$

From the output, it is clear that even though the rejected invalid character(i.e.,$) is not shown in the output, but they have been stored to the data buffer, so the next input for age is the data left in buffer i.e.,$$.
My Question : I want to confirm that is this behaviour expected in every case.i.e., Does the rejected characters always get stored to the data buffer ?

What I have tried:

I have tried it in 2-3 programs but i want to know whether is this always the case ?
That the rejected characters are stored in the buffer every time we use negated scanset.
Posted
Updated 15-Apr-16 4:58am
v2

1 solution

Any characters which are not used by the scanf format will remain in the buffer and will by "pulled" next time you call any method which retrieves characters from the same stream.
I.e. the behaviour you have seen is universal.
Similarly, if you use scanf to extract an integer from "123ABC" the "ABC" will remain in the buffer for next time.
 
Share this answer
 
Comments
Shubham_Dubey 15-Apr-16 11:01am    
Okk..Thanks a lot.
Please provide a link of the standard document discussing this behaviour.
OriginalGriff 15-Apr-16 11:05am    
Go use Google yourself!
Do you seriously think we're here to use a search engine for you?
Shubham_Dubey 15-Apr-16 11:14am    
Apologies sir, i didn't mean that.
Shubham_Dubey 15-Apr-16 11:04am    
I got confused because many sources, about "negated scanset" conversion specification, asserts that if the scanf encounters any invalid character it terminates reading the input.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900