2013-09-21 141 views
0

我试图写我的第一个计算器,并发现了一些在线的例子,然后我改变,使他们更容易在流动的条款。然而,当我改变这个流程:简单的计算器()

#include <stdio.h> 

main() 
{ 
    char operator; 
    float num1,num2; 

    printf("Enter an operator (+, -, *, /): "); 
    scanf("%c" ,&operator); 
    printf("Enter first operand: "); 
    scanf("%f" ,&num1); 
    printf("Enter second operand: "); 
    scanf("%f" ,&num2); 

    switch(operator) 
    { 
     case '+': 
      printf("num1+num2=%.2f\n" ,num1+num2); 
      break; 
     case '-': 
      printf("num1-num2=%.2f\n" ,num1-num2); 
      break; 
     case '*': 
      printf("num1*num2=%.2f\n" ,num1*num2); 
      break; 
     case '/': 
      printf("num1/num2=%.2f\n" ,num1/num2); 
      break; 
     default: //of operator is other than +, -, *, /, erros message shown 
     printf("Error! Invalid operator, this is basic math only.\n"); 
    }  
    return 0; 
} 

这样:

#include <stdio.h> 

main() 
{ 
    char operator; 
    float num1,num2; 


    printf("Enter first operand: "); 
    scanf("%f" ,&num1); 
    printf("Enter an operator (+, -, *, /): "); 
    scanf("%c" ,&operator); 
    printf("Enter second operand: "); 
    scanf("%f" ,&num2); 

    switch(operator) 
    { 
     case '+': 
      printf("num1+num2=%.2f\n" ,num1+num2); 
      break; 
     case '-': 
      printf("num1-num2=%.2f\n" ,num1-num2); 
      break; 
     case '*': 
      printf("num1*num2=%.2f\n" ,num1*num2); 
      break; 
     case '/': 
      printf("num1/num2=%.2f\n" ,num1/num2); 
      break; 
     default: //of operator is other than +, -, *, /, erros message shown 
     printf("Error! Invalid operator, this is basic math only.\n"); 
    }  
    return 0; 
} 

根本改变流从:进入运营商,然后输入第一个数字,然后第二个数字。要:输入第一个号码,然后输入运营商,然后输入第二个号码。 我的问题是,当我这样做时,我看到了Enter运算符,但程序跳过了输入运算符的选项并要求输入第一个数字,然后输入第二个数字。响应是默认开关。

+0

你看过[这个](http://stackoverflow.com/questions/14484431/scanf-getting-skipped?rq=1)的问题吗? – charmlessCoin

回答

0

您输入的换行符scanf读入您的第一个操作员正在采取的第二个scanf调用。有关更详细的解释,请参见this问题。

总之,写这样的功能,每一个scanf调用后调用它。

void clear_stdin(void) 
{ 
    while(getchar() != '\n'); 
} 
0

是因为换行符留在缓冲区内,当你进入第一个scanf的输入,所以下面scanf接受它,因为它的输入,只放了getchar()scanf()之后会解决它

0

输入缓冲区中留有新行。

使用scanf("%f",...时,%f消耗前导空白,但在数字后面没有尾随空白 - 通常是\n

当使用scanf("%c",...,该%c确实消耗领先的空白,并char之后没有尾随的空格要么。

为了消耗剩余的空白空间(例如来自先前的scanf()\n),简单地在%c之前加上一个空格。

// scanf("%c" ,&operator); 
scanf(" %c" ,&operator); // add space. 
+0

你是对的这个工作。这种现象的原因是什么?这是c语言中的一个旧bug吗?还是有目的地完成了这个任务并且有一个原因? –

+0

假设“这是一个老bug”中的“this”是指'%c'消耗空白:它不是一个错误。 '%c'扫描1'char',_any_ 1'char',没有例外,包括''''''\ n''等,甚至是''\ 0''(在阅读文本时很少遇到。 )为了避免在空格中扫描,预处理''''在'%c'之前消耗所有的空白。因此''%c“'不会存储空格。 '%c'允许使用'scanf()'扫描一个空格字符。 – chux