2016-10-18 69 views
0

我有一個簡單的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)它會顯示第一個字符,但表達式不會使用字符。

回答

1

當用戶進入輸入它將一個字符,隨後輸入鍵(\ n)的,收集的字符,從而當(INT C =的getchar()您可以不消耗\ n字符

; )

您還必須「吃」新行字符(getchar();)。

離開這個換行符可能導致外來輸出

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) 
    ... 
相關問題