2014-09-30 41 views
0

我正在開關操作員的幫助下制定一個加法,減法,除法和乘法程序。在這裏,我想製作一個只有當用戶輸入任何其他字符而不是'Y'時纔會停止的程序。問題是:當我運行程序時,在相應案例的結果之後,它只會打印'是否要繼續',之後程序會停止。請幫忙!先謝謝你! :)請解釋一下這個程序有什麼問題,我是新的

#include<stdio.h> 
int main() { 
    int n,a,b; 
    char answer; 
    while(1) { 
     printf("enter \n1.Addition \n2.subtraction \n3.division \n4.multiplication\t"); 
     scanf("%d",&n); 
     switch(n) { 
      case 1: { 
       printf("enter value of a and b:\t"); 
       scanf("%d %d",&a,&b); 
       printf("addition of %d+%d is %d",a,b,a+b); 
       goto ans; 
      } 
      case 2: { 
       printf("enter the value of a and b:\t"); 
       scanf("%d %d",&a,&b); 
       printf("Subtraction of %d-%d is %d",a,b,a-b); 
       goto ans; 
      } 
      case 3: { 
       printf("enter the value of a and b:\t"); 
       scanf("%d %d",&a,&b); 
       printf("Division of %*% is %d",a,b,a/b); 
       goto ans; 
      } 
      case 4: { 
       printf("enter the value of a nad b:\t"); 
       scanf("%d %d",&a,&b); 
       printf("Multiplication of %d*%d is %d",a,b,a*b); 
       goto ans; 
      } 
      default: printf("invalid value!"); 
      goto ans; 
     } 
     ans: { 
      printf("Do you want to continue?(Y/N):\t"); 
      scanf("%c",&answer); 
      if(answer=='Y') continue; 
      else break; 
     } 
    } 
    return 0; 
} 
+0

我編輯原始格式使用http://prettyprinter.de/module.php?name=PrettyPrinter – Antonio 2014-09-30 09:58:21

+4

你不應該使用'goto'。嘗試使用「while」循環或其他方式來檢查您的狀況。 – pzaenger 2014-09-30 09:59:44

+0

您的代碼顯示的警告類似於「30:6:警告:轉換在格式結尾處缺少類型[-Wformat]」 – Chandru 2014-09-30 10:10:00

回答

3

而是這個

scanf("%c",&answer); 

嘗試使用此:

scanf(" %c",&answer); 

在格式字符串中的空白吃掉了空格,換行,包括和讀取第一個非 - 空白字符。

+0

非常感謝! :)先生可以請你解釋一下這一行「格式字符串中的空白會佔用空白區域,包括換行符,並讀取第一個非空白字符」。它會非常棒! :) – 2014-09-30 11:36:30

+0

當你輸入一個符號時,最後還有一個新的符號。在你的情況下,碰巧scanf從前一個輸入(前一個scanf命令)接收到這個新的行符號。在格式化字符串之前添加空格符號,您要求scanf在開始時跳過所有空白符和換行符(如果有的話)。 – fycth 2014-09-30 12:30:10

+0

真棒比你好! – 2014-09-30 12:36:14

2

你是scanf處理的新行的受害者: scanf() leaves the new line char in buffer?

具體爲:
scanf函數試圖解析字符以外的東西之前,會自動刪除空白。字符格式(主要是%c)是例外(它們不會刪除空格),這就是您在上一次scanf中的情況。