2012-08-23 36 views
1

編輯:我不得不添加一個getchar();在scanf之後(「%i」,&選擇);現在它只要求一次!接受我的輸入並在while循環中比較它,fgets?

顯然它的案例開關導致它輸出兩次。如果我在外殼開關外部調用該功能,它將輸出1,但是如果我在開關內部調用它,則會輸出兩次

這是什麼原因造成的?我懷疑scanf的選擇?

#include <stdio.h> 
     #include <stdlib.h> 
     #include <string.h> 

     void test(); 
     void choose(); 
     int main(void) 
     { 
//if i call here its fine 
      test(); 
      choose(); 
      return 0; 
     } 

     void choose() 
     { 
      int choice; 

      do 
      { 
       printf("1 - Testing if double ask\n"); 
       printf("2 - Exit\n"); 
       printf("Please enter your choice: ");  
       scanf("%i", &choice); 

       switch(choice) 
       {//but pressing 1 here asks twice? 
        case 1:   
         test(); 
         break; 
        default: 
         if(choice !=2) 
          printf("Input Not Recognized!\n"); 
         break;   
       } 
      } 
      while(choice !=2); 
      if(choice == 2) 
       printf("Ciao!"); 
     } 
     void test() 
     { 
printf("HELLO"); 
       char *name = malloc (256); 

       do  
       { 
        printf("Would you like to continue (y/n)\n"); 
        fgets(name, 256, stdin); 
       } 
       while(strncmp(name, "n", 1) != 0); 
       free (name); 
     } 
+0

對單個字符或'strcmp()'使用單引號(如果它們相等,則它們將爲'0')。 – alex

+0

請在fgets後打印出姓名,並將其添加到帖子中。 – MWB

+0

@MWB ok,它的發佈 – Dog

回答

4

第一:你不能用比較操作!===比較C字符串。您需要爲此使用strcmp

此外,我想你會發現在這種情況下更有用的do { ... } while循環。在用戶有機會添加任何輸入之前,您正在檢查name一次。

接下來要注意的是,fgets將在您的輸入中保留換行符,因此您需要在使用strcmp時解決此問題。

+0

當你說換行符,你意思是說,當我輸入一個字母「a」時,它會像printf(「a \ n」)那樣? – Dog

+0

沒錯,輸入的字符串就像你的'printf'。 – pb2q

+0

啊,好吧,那我就不碰了因爲我需要在文本文件中逐行存儲 – Dog

1

字符串比較不會用C這樣的工作,你就必須string.h中使用的strcmp。

或者,您可以只看名字中的第一個字符。

while(name[0] != 'n') 
+0

我試過while(name [0]!='n',它的工作原理,謝謝,但它仍然問我兩次 – Dog

+0

你可以打印你讀的字符串嗎? – MWB