c - scanf read plus sign with integers but not minus, multiplication or division -
while writing arithmetic expression simplifier, observed odd behavior. recreated problem below:
#include <stdio.h> int main(void) { int n, i; char s[200]; for(i=0;i<2;i++){ if(scanf("%d", &n) == 1) { printf("%d\n", n); } else { scanf("%s", s); printf("%s\n", s); } } return 0; }
if input 5+10
reads 5
in n
, 10
in s
. but, other sign i.e 5-10
read 5
in n
, -10
in s
expected output.
my question is: c features caused this? checked on: gcc version 4.8.2 , ideone.
edit
solved problem char char reading of integers. time. :)
if interested: http://ideone.com/ropyqd
if input 5+10 reads 5 in n , 10 in s. but, other sign i.e 5-10 read 5 in n , -10 in s expected output.
you mistaken, determine changing printf()
statements can distinguish 1 generating each output. find program reading 5
n
in first iteration of loop, , reading either 10
or -10
n
, not s
on second iteration.
this happens because %d
field descriptor reads optionally signed decimal integer. "optionally signed" means preceded either -
negative or +
positive. thus, both "+10"
, "-10"
can scanned via %d
field.
Comments
Post a Comment