按下回车键时退出程序

时间:2016-10-18 02:54:20

标签: c++

我有一个简单的c ++计算器,我试图在空输入(Enter Key)上退出程序。我可以让程序退出并继续;但程序会忽略第一个字符。

#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);
}

我尝试使用putchar(c)它将显示第一个字符,但表达式不会使用该字符。

2 个答案:

答案 0 :(得分:1)

你可能没有消费\ n字符

当用户输入输入时,它将是一个字符,后跟输入键(\ n),因此在收集字符时(int c = getchar();)

然后你必须“吃掉”新行字符(getchar();)。

留下这个换行符可能会导致无关的输出

答案 1 :(得分:0)

正如hellowrld所说,代码中的内容可能类似:

...
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)
    ...