C user input only integers, return value from scanf -
i trying user input, , want make sure enter integers, , if don't ask them type again (loop until right).
i have found lot of different approaches this; more complicated others. found approach seems work.
but don't why tested in code:
scanf("%d%c", &num, &term) != 2
i can understand scanf
outputs number of items matched , assigned, don't why outputs 2 if integer.
the code in c is:
int main(void) { int num; char term; if (scanf("%d%c", &num, &term) != 2 || term != '\n') printf("failure\n"); else printf("valid integer followed enter key\n"); }
trying put in loop:
int main(void){ int m, n, dis; char m_check, n_check, dis_check; do{ m = 0; n = 0; dis = 0; m_check = ' '; n_check = ' '; dis_check = ' '; printf("please enter number of rows m in matrix (integer): "); if(scanf("%d%c", &m, &m_check) !=2 || m_check != '\n') m_check = 'f'; printf("please enter number of columns n in matrix (integer): "); if(scanf("%d%c", &n, &n_check) !=2 || n_check != '\n') n_check = 'f'; printf("should random numbers come uniform or normal distribution?... please press 1 uniform or 2 normal: "); if(scanf("%d%c", &dis, &dis_check) !=2 || dis_check != '\n' || dis != 1 || dis !=2) dis_check = 'f'; }while(m_check == 'f' || n_check == 'f' || dis_check == 'f');
i've tried inputting m = 3, n = 3, dis = 2, , loop starts on , asks me input number of rows. , if when asked press f or start looping crazy on printf-statements :)
entering integer match formatter %d
, assign value variable num
. %c
formatter take newline character ('\n') , store in variable term
. scanf
returns 2 cause 2 elements correctly assigned (num
, term
)
if don't enter integer formatter %d
won't match correctly, , scanf
won't return 2, producing failure
edit: do-while loop goes crazy cause conditions in last scanf wrong (dis != 1 || dis !=2
). should be
if(scanf("%d%c", &dis, &dis_check) !=2 || dis_check != '\n' || (dis != 1 && dis !=2))
Comments
Post a Comment