【问题标题】:Exit program when enter key is pressed按下回车键退出程序
【发布时间】:2016-10-18 12:29:39
【问题描述】:

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

#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) 它将显示第一个字符,但表达式不会使用该字符。

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可能没有使用 \n 字符

    当用户输入输入时会是一个字符后跟回车键(\n),所以在收集字符时(int c = getchar();)

    您还必须“吃掉”换行符 (getchar();)。

    留下这个换行符可能会导致多余的输出

    【讨论】:

      【解决方案2】:

      正如 hellorld 所说,您的代码中可能是这样的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-22
        • 2014-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多