2013-11-22 58 views
-4

如果你往下看主函數,錯誤在於第一個輸入。 當我輸入\ q時,我的程序並沒有像我希望的那樣終止。不知道爲什麼程序不會終止

誰能給我解釋一下爲什麼會發生?

我發現,如果我改變與fgets到scanf函數,則\ q部分工作得很好,但後來(與scanf函數),如果我輸入任何空格的字符串我輸入一個空格後終止。

#include <stdio.h> 
#include <cstring> 
#include <ctype.h> 


int count(char *input, char c) { 
    int k = strlen(input); 
    return 0; 
} 



void subanagram() { 
    char yes[50] = "yes"; 
    char no [50] = "no"; 
    char play[100]; 
    char sa[100]; 
    char strin[100]; 
    char quitt[75] = { '/', 'q', '\0'}; 

    do { 
    printf("Would you like to play the sub-anagram game?"); 

    //scanf("%s", play); 
    fgets(play, 100, stdin); 

    if(stricmp(play, yes) == 0) { 
     printf("Enter a potential sub-anagram (or /q to quit): "); 
     scanf("%s", sa); 

     if(stricmp(sa, quitt) == 0) { 
      break; 
     } 

    } 




} 
while (stricmp(yes, play) == 0 || stricmp(no, play) == 0); 
} 

void main() { 
    char string[100]; 
    char pally[75]; 
    char nospace[100]; 
    char reversed[100]; 
    char yes[75] = {'y', 'e', 's', '\0'}; 
    char quit[75] = { '\\', 'q', '\0'}; 
    char no[75] = {'n', 'o', '\0'}; 
    char play[50]; 
    int p, i, k, j=0; 

    printf("Enter a word or phrase (or \\q to quit): "); 
    fgets(string, 100, stdin); 
    //scanf("%s", string); 

    k = strlen(string); 

    if(stricmp(quit, string) == 0) { 
     printf("Thank you for using my program!\n"); 
     return; 
    } 

    do { 
     printf("Would you like to see if the phrase is a palindrome?"); 
     scanf("%s", pally); 
    } while (stricmp(yes, pally) == 1 || stricmp(no, pally) == 1); 

    if(stricmp(yes, pally) == 0) { 


     for(i=0; i<k; i++) { 
      if(!isspace(string[i]) == 1) { 

       nospace[j] = string[i]; 
       nospace[j+1] = '\0'; 
       j++; 

     } 
    } 
       strcpy(reversed, nospace); 
       strrev(reversed); 

       if(stricmp(nospace, reversed) == 0) { 
        printf("The phrase %s IS a palindrome.\n", string); 
        subanagram(); 
       } 

       else { printf("The phrase %s IS NOT a palindrome.\n", string); 
        subanagram(); 
       } 


    } 
     if(stricmp(pally, no) == 0) { 
    /* printf("Would you like to play the sub-anagram game?"); 
     scanf("%s", play); 
     if(strcmp(play, yes) == 0) { 
      subanagram(); 
     }*/ 
     subanagram(); 
    } 
} 
+0

請縮進代碼(這順便說一句是fo,從而過大),所以它是可讀的,人們可以看到相應的塊! –

回答

0

嗯,就先在這(太)大項目找我對稱的探測器看到了subanagram():

{ '/', 'q', 
"...(or /q to quit): " 

,並在主要是:

char quit[75] = { '\\', 'q', 

和您的問題是:

"When I type \q, my program does not" 
0

'\n'(字符爲換行符)作爲您輸入的字符串將包含在fgets(stinrg, 100, stdin)的情況下,與scanf("%s", string)不同。所以,退出字符串更改爲char quit[] = "\\q\n"或者您刪除最後的\n',則確定它必須是一種處理方式,如果您願意。

相關問題