2014-11-21 58 views
0

我有這個小程序:請與fgets字符保存到一個變量用C

char buffer[10] = "0" 
while (buffer == "0"){ 
fgets(buffer, sizeof(buffer), stdin); 

if(buffer == "1\n") do this 
if(buffer == "2\n") do that 
} 

然而,當我按1或2(或任何其他爲此事),沒有任何反應。 我錯過了什麼?

+0

使用'strcmp'比較字符串。 – 2014-11-21 07:33:57

+0

您不能使用'=='來比較C中的字符串 - 而是使用strcmp。 – 2014-11-21 07:34:04

回答

-1

while (buffer == "0")

這裏,我想,你是期待

while(strcmp(buffer,"0")==0) .//您可以更改條件

1

變化

char buffer[10] = "0" 
while (fgets(buffer, sizeof(buffer), stdin){ 
    if(strcmp(buffer, "1\n")==0) 
     ;//do this 
    if(strcmp(buffer, "2\n")==0) 
     ;//do that 
} 
0

其他人已經告訴你,你無法將字符串與==進行比較。在你的情況下,如果你想寫一個菜單,你可以先將緩衝區轉換爲數字,然後用sscanfatoi

這裏有一個簡單的實現這樣一個菜單:

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

int main() 
{ 
    char buffer[10]; 
    int done = 0; 

    while (!done) { 
     int option = 0; 

     puts("1. Do this"); 
     puts("2. Do that"); 
     puts("3. Quit\n"); 

     if (fgets(buffer, sizeof(buffer), stdin) == NULL) break; 
     if (sscanf(buffer, "%d", &option) < 1) option = 0; 

     switch (option) { 
     case 1: 
      puts("Done this.\n"); 
      break; 

     case 2: 
      puts("Done that.\n"); 
      break; 

     case 3: 
      done = 1; 
      break; 

     default: 
      puts("Please enter one of 1, 2, 3\n"); 
     } 
    } 

    puts("Bye!"); 
    return 0; 
} 
相關問題