954,535 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

noob char input problem

I'm using the latest VS C++ express edition for a basic intro to c++ class that is largely focused on numerical applications. Anywho, for whatever reason, I'm getting strange behavior from scanf("%c",&whatever). The program is supposed to use switch to perform some operations on input integers, but way before I can get there, it has a problem -- the scanf("%c"... deal seems to automatically get bypassed and the program quits (press any key). What's strange is that if I switch the order of the scanf's, s.t. the scanf("%c"... comes before the %d scanf's, everything is fine. What am I missing here?

int num1,num2;
    char o;
    float rslt;    
    printf("Enter 1st integer: ");
    scanf("%d",&num1);
    printf("Enter 2nd integer: ");
    scanf("%d",&num2);
    printf("Choose operation <a,s,m,d>: ");
    scanf("%c", &o);
    printf("\n%c",o);
isaacmacdonald
Newbie Poster
5 posts since Jun 2006
Reputation Points: 18
Solved Threads: 0
 
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Since all you are reading is a character, use getchar() . But remember that you did hit the ENTER key too. You therefore have to clear the buffer. So when you read a character, use something like

whatever = getchar();  // at least one character left in the input stream
do
{
    dummy = getchar();    // read another character
} while (dummy != '\n');  // stop when newline is read
WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You