Reputation: 16047
Is there a way to force sscanf to NOT allow extra whitespace.
Following code accepts "N_ 234"
, even though it should only accept "N_234"
:
int r;
unsigned b;
r = sscanf("N_ 234", "N_%u", &b); /* Returns 1 */
Tested with IAR compiler.
Upvotes: 4
Views: 171
Reputation: 58281
May be my code helpful to you:
# define SIZE 100
int main(){
int r;
unsigned b = 0u;
char s[SIZE] = {0};
sscanf("N_234", "%[N_0-9]", s);
r = sscanf(s,"N_%u",&b);
printf("%u\n",b);
}
printf("%u\n",b);
output correct value if there no space and r
is 1, otherwise b
= 0 and r
is -1 (EOF).
Give it a try!!
EDIT: There is chance of e buffer overrun but can be corrected using dynamic allocation.
Upvotes: 1
Reputation: 61
Try this:
int r;
unsigned b;
char c[20];
r = sscanf("N_ 234", "N_%[0-9]", c); /* Returns 0 */
r = sscanf("N_-234", "N_%[0-9]", c); /* Returns 0 */
r = sscanf("N_1234", "N_%[0-9]", c); /* Returns 1 */
b = atoi(c);
Upvotes: 2