Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 131,710 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,401 people online right now. Registration is fast and FREE... Join Now!




getchar() function

2 Pages V  1 2 >  
Reply to this topicStart new topic

getchar() function

aaru_89
post 13 Oct, 2006 - 09:03 AM
Post #1


New D.I.C Head

*
Joined: 26 Sep, 2006
Posts: 20



Thanked 1 times
My Contributions


Hello. I wrote the following part of my code to continue the program if the user entered 'Y' and terminate otherwise.

CODE

#include<stdio.h>
#include<conio.h>
void main
{
    char c[1];
    printf("\n Enter Y/N");
    //scanf("%s",&c);
    c=getchar();
    if(c=="Y")
        printf("\n Program continues...");
    else
        printf("\n Program terminates...");
    getch();
}



When I tried to compile, it showed an error which read "Lvalue required in function main".
I tried using scanf(), but then, whatever maybe the input, the output was "Program terminates".

Can someone please explain the correct use of getchar() and also the solution for my problem? Thanks.

This post has been edited by aaru_89: 13 Oct, 2006 - 09:05 AM
User is offlineProfile CardPM

Go to the top of the page

Amadeus
post 13 Oct, 2006 - 09:13 AM
Post #2


g++ -o drink whiskey.cpp

Group Icon
Joined: 12 Jul, 2002
Posts: 12,163



Thanked 32 times

Dream Kudos: 25
My Contributions


If you are comparing a value to a char, you'll wish to use single quotes...

CODE

if(c=='Y')

Also, as a single char, it does not need to be declared as an array.
User is offlineProfile CardPM

Go to the top of the page

aaru_89
post 13 Oct, 2006 - 09:37 AM
Post #3


New D.I.C Head

*
Joined: 26 Sep, 2006
Posts: 20



Thanked 1 times
My Contributions


I still don't get it. When I tried compiling the code separately as follows,

CODE

#include<stdio.h>
#include<conio.h>
void main()
{
    char c;
    printf("\n Enter Y/N");
    c=getchar();
    if((c=='Y')||(c=='y'))
        printf("\n Program continues...");
    else
        printf("\n Program terminates...");
    getch();
}


it compiled and ran with no problem at all.

But when I use it as part of my code, it does not work. The rest of the program works though. Can someone please explain why this happens?
User is offlineProfile CardPM

Go to the top of the page

Amadeus
post 13 Oct, 2006 - 09:40 AM
Post #4


g++ -o drink whiskey.cpp

Group Icon
Joined: 12 Jul, 2002
Posts: 12,163



Thanked 32 times

Dream Kudos: 25
My Contributions


If the code you posted works on its own, but not when integrated with other code, logic suggests that the other code may present the problem.

Can you post the rest of the code? and specify what compiler/OS you are using?

Also, it should be noted that in your original posting, the declaration of your main function did not have the required brakets afterwards (where parameters would be supplied).
User is offlineProfile CardPM

Go to the top of the page

aaru_89
post 13 Oct, 2006 - 09:49 AM
Post #5


New D.I.C Head

*
Joined: 26 Sep, 2006
Posts: 20



Thanked 1 times
My Contributions


Here's the full code. The initial part is just to calculate the cell bill of the user. Nothing much in that and it works fine. It's the last looping part that's troubling.

CODE

#include<stdio.h>
#include<conio.h>

void main()
{
    int c,p,t;
    float a;
    char w;
    printf("\n What connection are you using? \n 1.Airtel \n 2.Aircel \n 3.Hutch \n 4.Idea \n 5.BSNL\n ");
    scanf("%d",&c);
    if((c!=1)&&(c!=2)&&(c!=3)&&(c!=4)&&(c!=5))
    {
        printf("\n Invalid choice. Try again\n ");
        main();
    }
    else
    {
        printf("\n Select payment option \n 1.Postpaid \n 2.Prepaid\n ");
        scanf("%d",&p);
        printf("\n Enter talk time in minutes\n ");
        scanf("%d",&t);
        switch(c)
        {
            case(1):
            {
                if(p==1)
                    a=t*.95;
                if(p==2)
                    a=t*.99;
                printf("\n Your bill is Rs. %5.2f",a);
               break;
            }
            
            case(2):
            {
                if(p==1)
                    a=t*.90;
                if(p==2)
                    a=t*.95;
                printf("\n Your bill is Rs. %5.2f",a);
                break;
            }
            
            case(3):
            {
                if(p==1)
                    a=t*.97;
                if(p==2)
                    a=t*1.0;
                printf("\n Your bill is Rs. %5.2f",a);
                break;
            }
            
            case(4):
            {
                if(p==1)
                    a=t*.95;
                if(p==2)
                    a=t*.98;
                printf("\n Your bill is Rs. %5.2f",a);
                break;
            }
            
            case(5):
            {
                if(p==1)
                    a=t*1.0;
                if(p==2)
                    a=t*1.02;
                printf("\n Your bill is Rs. %5.2f",a);
                break;
            }
        }

                
    printf("\n Do you wish to continue(Y/N): ");
    w=getchar();
    if((w=='Y')||(w=='y'))
        {
            printf("\n Welcome again");
            main();
        }
    else
        printf("\n Have a nice day. Thank you.");
    }
    getch();
}



I am using gcc/windows xp. Thanks.
User is offlineProfile CardPM

Go to the top of the page

Amadeus
post 13 Oct, 2006 - 09:57 AM
Post #6


g++ -o drink whiskey.cpp

Group Icon
Joined: 12 Jul, 2002
Posts: 12,163



Thanked 32 times

Dream Kudos: 25
My Contributions


First and foremost, I must strongly advise against calling main from the main fucntion...this recursively calls the program, and while legal in C (illegal in C++), it is eextremely ill advised and almost never a good idea.

As to the problem at hand, you have asked the user for several peices of information, which the user is supplying via standard input. It is likely that there is still a character in the buffer when you try to assign a value to w (perhaps the newline character)...a good test would be to place a second getchar() call immediately before the first...see what happens.
User is offlineProfile CardPM

Go to the top of the page

aaru_89
post 13 Oct, 2006 - 10:10 AM
Post #7


New D.I.C Head

*
Joined: 26 Sep, 2006
Posts: 20



Thanked 1 times
My Contributions


Thank you very much for your help Amadeus. My code works properly now. But can you please explain why it went awry previously? I'm sorry if I'm pestering too much, but I'm new to C and have a problem with my basics. Thanks again.
User is offlineProfile CardPM

Go to the top of the page

Amadeus
post 13 Oct, 2006 - 10:19 AM
Post #8


g++ -o drink whiskey.cpp

Group Icon
Joined: 12 Jul, 2002
Posts: 12,163



Thanked 32 times

Dream Kudos: 25
My Contributions


As mentioned, the problem is likely that there is residual data in the input buffer. You have asked the user for several pieces of information, which the user has entered via the buffer (input stream via keyboard). the buffer holds the items entered by the user, including things like the newline character or other garbage. When you prompt for program continuation, you are using the getchar() function to take the input...but there is likely already something left in the buffer...the getchar() function takes the first character in the buffer, and proceeds. It looks as if it is skipping the input portion, but really, the getchar() function has pulled a value from the buffer and processed it.

And you can never pester too much! That's what these forums are for, so you're more than welcome to ask as many questions as you like! smile.gif
User is offlineProfile CardPM

Go to the top of the page

aaru_89
post 13 Oct, 2006 - 10:39 AM
Post #9


New D.I.C Head

*
Joined: 26 Sep, 2006
Posts: 20



Thanked 1 times
My Contributions


Also, is there an alternative instead of calling main() recursively? It works fine in this code but will there be any serious problem because of it? I am stumped and can't think of anything. Thanks.
User is offlineProfile CardPM

Go to the top of the page

Amadeus
post 13 Oct, 2006 - 11:03 AM
Post #10


g++ -o drink whiskey.cpp

Group Icon
Joined: 12 Jul, 2002
Posts: 12,163



Thanked 32 times

Dream Kudos: 25
My Contributions


There is likely not going to be any negative consequence in this case...as I said, this action is permitted in C, but can lead to undefined behaviour. You can accomplish the same effect by changing the program structure slightly, performing the error checking and prompts in a loop. Something like:
CODE

char w = 'Y';
while(w=='Y'||w=='y')
{
   /*your code here*/
   printf("\n Do you wish to continue(Y/N): ");
   w=getchar();
}
User is offlineProfile CardPM

Go to the top of the page

gregoryH
post 13 Oct, 2006 - 01:56 PM
Post #11


D.I.C Regular

Group Icon
Joined: 4 Oct, 2006
Posts: 417



Dream Kudos: 50
My Contributions


A small improvement on Armadeus code is:
CODE
while ( toupper ( w ) =='Y' )
{
   /*your code here*/
   printf("\n Do you wish to continue(Y/N): ");
   w=getchar();
}
User is offlineProfile CardPM

Go to the top of the page

janotte
post 13 Oct, 2006 - 02:43 PM
Post #12


New D.I.C Head

*
Joined: 28 Sep, 2006
Posts: 26


My Contributions


I think Amadeus' solution of using loops within main() is a better answer than what follows but it you wanted to keep your recursion idea without calling main() a quick and dirty way would be:

CODE


#include<stdio.h>
#include<conio.h>

//  function prototype
void MyFunction();

void main()
{
    // call the declared function
   MyFunction();
}

// the full function
void MyFunction()
{
  // all the code you have in your main() pasted into here
  //    but change the recursive call to main() to
  //    a call to MyFunction()
}



Now the recursion is happening in and to MyFunction() instead of main().

But, as I said, the loop idea within main() is a superior solution for your program.

This post has been edited by janotte: 13 Oct, 2006 - 02:56 PM
User is offlineProfile CardPM

Go to the top of the page

2 Pages V  1 2 >
Reply to this topicStart new topic
Time is now: 11/20/08 09:34AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month