c - scanf won't terminate with hex values? -
when run code:
main(){ int hex; printf("enter 4 hex values:\n"); while(scanf("%x", &hex) == 1) { body } } it runs body of code, shows cursor , user can input more data until enter null. how can fix while loop once user enters data, 014c 456b 0894 0011 (some random hex numbers), body , program terminates? i.e., why loop ending when user inputs null , how fix this?
you call scanf() until error or eof (it test number of values — marks that). if want call 4 times, have limit separately:
int main(void) { int hex; printf("enter 4 hex values: "); (int = 0; < 4 && scanf("%x", &hex) == 1; i++) { …body… } return 0; } note use of &hex instead of hex in call scanf(); need pass pointer (but if object array, string, pass name without & in front).
if need detect whether exited before getting 4 values, define i outside loop , test afterwards.
also note explicit return type main(); required current , previous versions of c standard. archaic, quarter-century old first version of standard allowed implicit int. , standard required return value main() modern ones let off hook (more's pity, imo).
Comments
Post a Comment