c - Need help understanding while loops -
let's have simple code begins like:
#include <stdio.h> int main() { char c; int x; printf("num here: "); c = getchar(); x = 0; while (c!=eof) { x = c - 48; //to convert x ascii
in program, i'm trying user type number (ex. 42) , trying add ones digit tens (and hundreds, etc.); i'm having lot of trouble understanding how can while loop go loop until end of number.
so, need lot of understanding how can loop read until end of character, read char input user puts in number (42), , then, treat numbers individually using getchar().
normally, you'd use:
int c; // because getchar() returns int, not char int x = 0; while ((c = getchar()) != eof) { if (isdigit(c)) x = x * 10 + (c - '0'); else ... }
this reads character each time reaches top of loop. loop go running brace @ end of loop (or, occasionally, using continue
statement). might exit loop break
, example if read character can't part of number.
if user types 42
(followed enter), first read c == '4'
, c == '2'
, read newline '\n'
. every digit '0'
'9'
, digit - '0'
yields number corresponding digit. newline can't part of number, either put ungetc(c, stdin)
or break loop when you've read it.
beware of overflow if user types 43219876543 expected 42 (and int
32-bit quantity).
you write loop condition as:
while ((c = getchar()) != eof && isdigit(c))
or even:
while (isdigit(c = getchar()))
i'd extremely reluctant put latter production code is, in theory, safe.
how treat each number individually can use entirety of numbers later on? if user types
10 20 30
, can multiply10
20
, (10*20
)30
?
wheels within wheels — or loops within loops. you'll need specify criteria bit. if user types 1
want answer 1
; if type 1 2
, want 2
; if type 1 2 3
, want 6
; , on (where these numbers on single line of input). you'll need outer loop skips on blanks , tabs, uses inner loop read number, , multiplies current product (initial value 1
) new number, , after outer loop, you'll print product. print 1
empty line; maybe doesn't matter (and maybe does).
here's code approximates appropriate:
#include <ctype.h> #include <stdio.h> int main(void) { int c; while ((c = getchar()) != eof && c != '\n') { int product = 1; while (c != eof && c != '\n') { while (isspace(c)) c = getchar(); int number = 0; while (isdigit(c)) { number = number * 10 + (c - '0'); c = getchar(); } printf("number: %d\n", number); product *= number; } printf("product: %d\n", product); } return 0; }
i tried version different 'skip' loop:
while (c != eof && c != '\n' && !isdigit(c)) c = getchar();
both work ok on sane inputs. empty lines treated end of input; lines containing blanks not. if input 1a2b3c
second condition, output 0
; first, infinite loop. there no overflow protection; don't try doing factorial 20 , expect correct answer (with 32-bit int
). tweak heart's content.
Comments
Post a Comment