简体   繁体   中英

Exit program when enter key is pressed

I have a simple c++ calculator and I am trying to have the program exit on empty input (Enter Key). I can get the program to exit and continue; however the program ignores the first character.

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <conio.h>

using namespace std;
float a, b, result;
char oper;
int c;


void add(float a, float b);
void subt(float a, float b);
void mult(float a, float b);
void div(float a, float b);
void mod(float a, float b);


int main()
{
// Get numbers and mathematical operator from user input
cout << "Enter mathematical expression: ";

int c = getchar(); // get first input
if (c == '\n') // if post inputs are enter
    exit(1); // exit

else {

    cin >> a >> oper >> b;


    // operations are in single quotes.
    switch (oper)
    {
    case '+':
        add(a, b);
        break;

    case '-':
        subt(a, b);
        break;

    case '*':
        mult(a, b);
        break;

    case '/':
        div(a, b);
        break;

    case '%':
        mod(a, b);
        break;

    default:

        cout << "Not a valid operation. Please try again. \n";
        return -1;

    }


    //Output of the numbers and operation
    cout << a << oper << b << " = " << result << "\n";
    cout << "Bye! \n";
    return 0;
}
}

//functions
void add(float a, float b)
{
result = a + b;
}

void subt(float a, float b)
{
result = a - b;
}

void mult(float a, float b)
{
result = a * b;
}

void div(float a, float b)
{
result = a / b;
}

void mod(float a, float b)
{
result = int(a) % int(b);
}

I tried using putchar(c) it will display the first character, but the expression wont use the character.

You may not be consuming the \\n character

When the user enters input it will be a character followed by the enter key (\\n), so when collecting the character (int c = getchar();)

You must then also "eat" the new line character (getchar();).

Leaving this newline character may lead to extraneous output

As hellowrld said, it can be something like that in your code:

...
if (c == '\n') // if post inputs are enter
    exit(1); // exit

else
{
    // Reads all input given until a newline char is
    // found, then continues
    while (true)
    {
        int ignoredChar = getchar();
        if (ignoredChar == '\n')
        {
            break;
        }
    }

    cin >> a >> oper >> b;


    // operations are in single quotes.
    switch (oper)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM