Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

getchar ??

Posted on 1999-07-11
8
Medium Priority
?
393 Views
Last Modified: 2013-12-27
i had written the below simple prog . however i am facing a prob .

the prog is

 #include<stdio.h>
 #include<string.h>
void main()
{
int i,j;
char num[10],ch='y';
while(ch=='y'||ch=='Y')
{
printf("\n enter the number ");
scanf("%s",num);
j=strlen(num);
for(i=0;i<=j;i++)
switch(num[i])
{
 case '0':printf(" zero "); break;
 case '1':printf(" one "); break;
.
.
.
.
case '9':printf(" nine ");
default: printf(" invalid number");
}
printf(" want to enter an other num");
ch=getchar();
}
}

the prob is that it is not waiting for me to enter a char after getchar it is directly going to the $ prompt. i think it is the buffer problem. how to clear the buffer. flushall does not work.how to do it with getchar. i then declared ch as string i.e array of 1 char. then it worked just fine.
i am working on sun os 5.6 c version 4.something
0
Comment
Question by:team
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 

Author Comment

by:team
ID: 2011446
i am still going crazy
0
 
LVL 2

Accepted Solution

by:
bedot earned 100 total points
ID: 2011447
getchar (which is defined in stdio.h) is a macro:

      getc()         Returns the next character (i.e., byte) from the named
                     input stream, as an unsigned character converted to an
                     integer.  It also moves the file pointer, if defined,
                     ahead one character in stream.  getchar() is defined as
                     getc(stdin).  getc() and getchar() are defined both as
                     macros and as functions.

#    define getchar()   getc(stdin)

so, try
#include <stdio.h>
main()
{
 int i;
 while ((i=getchar())!='\n')
    {
     putchar(i);
     printf ("hex=%d\n",i); /* for viewing the hex value returned */
    }
}

this program MUST run while you don't  type a return (stty OCRNL which maps CR to NL==\n)
take care at the parameters of the intelligent I/O interface (my response to your precedent question: c_cc[VMIN] that permit to return with 1 character and also the flag permitting return after tomeout)
0
 

Expert Comment

by:kannan042597
ID: 2011448
Just add one more getchar() next to
  ch=getchar();
line.  This is because, getchar takes, your character for the first time input and then the ENTER key as the next character in the buffer, due to which the while loop fails.

Try the following code: It will work.


#include<stdio.h>
 #include<string.h>
void main()
{
int i,j;
char num[10],ch='y';
while(ch=='y'||ch=='Y')
{
printf("\n enter the number ");
scanf("%s",num);
j=strlen(num);
for(i=0;i<=j;i++)
switch(num[i])
{
 case '0':printf(" zero "); break;
 case '1':printf(" one "); break;
.
.
.
.
case '9':printf(" nine ");
default: printf(" invalid number");
}
printf(" want to enter an other num");
ch=getchar();
getchar();
}
}





Regards
Kannan.

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Expert Comment

by:pagladasu
ID: 2011449
All you need to do is add the line:
fflush(stdin);
after the scanf() statement.

hope this helps,
thanks,
pagladasu
0
 
LVL 2

Expert Comment

by:bedot
ID: 2011450
while ((i=getchar())!='\n')
surely take care of \r (return) because we are here under unix and the I/O peripheral is  in  icrnl mode that maps inputing CR into NL  like this example:


root@med1091[/]stty -a
speed 9600 baud; line = 0;
rows = 24; columns = 80
min = 4; time = 0;
intr = ^C; quit = ^\; erase = ^H; kill = ^U
eof = ^D; eol = ^@; eol2 <undef>; swtch <undef>
stop = ^S; start = ^Q; susp <undef>; dsusp <undef>
werase <undef>; lnext <undef>
parenb -parodd cs7 -cstopb hupcl -cread -clocal -loblk -crts
-ignbrk brkint ignpar -parmrk -inpck istrip -inlcr -igncr icrnl -iuclc
ixon -ixany ixoff -imaxbel -rtsxoff -ctsxon -ienqak
isig icanon -iexten -xcase echo echoe echok -echonl -noflsh
-echoctl -echoprt -echoke -flusho -pendin
opost -olcuc onlcr -ocrnl -onocr -onlret -ofill -ofdel -tostop
root@med1091[/]

0
 

Expert Comment

by:donner
ID: 2011451
There is a logic error in your program.  You have the looping construct

   while( ch=='y'||ch=="y' )

which loops while the character is upper or lower case y.  This
loop will fail immediately because it gets the uninitialized value
of ch, which is probably NUL.

To fix the program, simply change the while to until and you'll be fine.
No need to go for something sophisticated like flushing the buffer.

0
 
LVL 84

Expert Comment

by:ozo
ID: 2011452
ch was initialized to 'y'
0
 

Expert Comment

by:donner
ID: 2011453
Well, I just tried it.  I inserted the line:

   printf( "I got: %x\n", ch );

right after your getchar() and lo and behold, it told me that
the following character was 0x0A, or linefeed.  That is, the
scanf took the number and the carriage return, leaving the
linefeed in the input stream.  The next getchar got the linefeed
(remember, in UNIX the end-of-line is CR-LF), which is why
your program logic failed.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Regular patching is part of a system administrator's tasks. However, many patches require that the system be in single-user mode before they can be installed. A cluster patch in particular can take quite a while to apply if the machine…
FreeBSD on EC2 FreeBSD (https://www.freebsd.org) is a robust Unix-like operating system that has been around for many years. FreeBSD is available on Amazon EC2 through Amazon Machine Images (AMIs) provided by FreeBSD developer and security office…
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
Learn how to get help with Linux/Unix bash shell commands. Use help to read help documents for built in bash shell commands.: Use man to interface with the online reference manuals for shell commands.: Use man to search man pages for unknown command…

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question