hi all,
Hereunder two versions of reading a word from stdin stream:
/* code starts */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char *
getnumber1(void); /* return a word from stdin */
void
getnumber2(char *); /* read a word from stdin and store it in the char*
*/
int main()
{
int i = 0;
char w[20];
i = atoi(getnumber1());
printf("getnumber1 = %d\n", i);
i = 0;
getnumber2(w);
i = atoi(w);
printf("getnumber2 = [%s]\n", w);
printf("getnumber2 = %d\n", i);
return 0;
}
char *
getnumber1(void)
{
char w[20];
char *p;
int c;
p = w;
while (isspace(c = getchar()))
;
if (c != EOF)
*p++ = c;
for (;;) {
if (isspace(c = getchar())) {
ungetc(c, stdin);
break;
}
*p++ = c;
}
*p = '\0';
printf("getnumber1 = [%s]\n", w);
return w;
}
void
getnumber2(char *w)
{
char *p;
int c;
p = w;
while (isspace(c = getchar()))
;
if (c != EOF)
*p++ = c;
for (;;) {
if (isspace(c = getchar())) {
ungetc(c, stdin);
break;
}
*p++ = c;
}
*p = '\0';
return;
}
/* code ends */
I use bc++5.5 as compiler.
the input and output of this small program is like this:
D:\c\scan>getnum
12
getnumber1 = [12]
getnumber1 = 1
12
getnumber2 = [12]
getnumber2 = 12
You can see that results of getnumber1 and getnumber2 are the same.
(12)
but the output of atoi are diffrent.
Can anyone do me a favor to explain the diffrence?
Thanx and
Regards,
jigsaw