AH it just clicked! I get it now. Thanks everybody.
Printable View
AH it just clicked! I get it now. Thanks everybody.
instead of clearing input using getchar - it is possible to use
fgets/sscanf instead, and avoid clearing problem at all
Quite nice -- I think the only thing I would have done differently would be to use size_t in a few places instead of int, because sizeof evaluates to values of type size_t. Note that if you had compiler warnings enabled it would probably warn you about signed/unsigned type mismatches, because size_t is an unsigned type and int is a signed type (and thus comparing them as in "i < sizeof(item)/sizeof(*item)" might not work for very large or negative values).
What vart says is true, too. The fgets method would probably make your life easier in the end.
That's all there is to handling EOF and everything.Code:char buffer[BUFSIZ]; /* BUFSIZ is a constant defined in stdio.h, at least 512 in size */
while(fgets(buffer, sizeof buffer, stdin)) {
if(sscanf(buffer, "%d", &number) == 1) {
printf("%d\n", number);
}
else {
printf("Error: please enter a number\n");
}
}
I get no warnings whatsoever. I checked my compile settings in regards to warnings and even checked everything that was available for checking. Still no warnings.
Where does the newline come from in
?Code:while(getchar() != '\n') {}
do you feed a \n into input when you press enter? I thought that was called a carriage return?
> do you feed a \n into input when you press enter?
yes.
> I thought that was called a carriage return?
that's \r. When you press enter, some machines give a \n, some an \r, some an \r\n. But on text streams (as opposed to binary streams) like stdin, the newline sequence is always translated to \n.
That's strange. Here's what I get. The blue warning is the one I was talking about.Quote:
I get no warnings whatsoever. I checked my compile settings in regards to warnings and even checked everything that was available for checking. Still no warnings.
If you can add warning flags directly, I suggest -W and -Wall. (If you put -ansi and -pedantic, it will always warn about single-line comments. Unless you use -std=c99.)Code:$ gcc -pedantic -W -Wall dino1.c -o dino1
dino1.c:49:3: warning: C++ style comments are not allowed in ISO C90
dino1.c:49:3: warning: (this will be reported only once per input file)
dino1.c: In function ‘main’:
dino1.c:51: warning: comparison between signed and unsigned