2013-10-31 33 views
-1

我怎樣才能用我的while循環條件運行我自己的原型函數?原型函數與我的while循環條件錯誤C

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

msghere(char *text){ 
    printf("%s",text); 
    return 0; 
} 
void main(){ 
    char inp[256]={0}; 
    clrscr(); 
    while(strcmp(inp,"pass") && msghere("Error!")){ 
     memset(inp,0,strlen(inp)); 
     printf("Type \"pass\": "); 
     gets(inp); 
    } 
    msghere("Right Answer!"); 
    getch(); 
} 

此代碼打印的輸出:

Error!Right Answer! 
+0

1)不要使用'gets',而應該使用['fgets'](http://en.cppreference.com/w/c/io/fgets)。 2)用返回類型聲明'msghere'(你的情況是'int')。 3)爲了避免將來出現這些錯誤:在啓用所有警告的情況下進行編譯(GCC爲'-Wall')。 – Kninnug

回答

2

你想要的是一個do-while循環,並像一個if條件的東西。

int msghere(char *text){ 
    printf("%s",text); 
    return 1; 
} 
int main(void) 
{  
    do 
    { 
    //your code 
    }while((strcmp(inp, "pass") == 0 ? 0 : msghere("error!"))); 
} 

爲什麼do-while?
因爲您希望您的用戶在第一次檢查之前進行輸入。邏輯權利?

WTF是「while((strcmp(inp, "pass") == 0 ? 0 : msghere("error!")))」?
首先:錯誤的編碼風格。這是一個簡短的版本if/else。如果第一個條件爲真,則返回?否則返回值:

爲什麼返回1;在msghere()?
因爲你的while while循環會評估是否有錯誤。錯誤== True - >再次執行。

你應該做的:
是類似以下內容:

// your original msghere 
int main(void) 
{ 
    int passed = 0; //false 
    // some code 
    while(!passed) //while not passed 
    { 
    //read input with fgets like said in the comments 
    if(strcmp(inp, "pass") == 0) 
    { 
     passed = 1; // true 
    } 
    else 
    { 
     msghere("error"); 
    } 
    } 
} 

它使用的狀態變量並且更加easyier閱讀。

1
#include <stdio.h> 
#include <conio.h> 
#include <string.h> 

int msghere(const char *text) 
{ 
    printf("%s",text); 
    return 1; /* you want 1 instead of 0, because (strcmp != 0) && 1 == true */ 
} 

int main(void) 
{ 
    char inp[256]; 

    clrscr(); 
    do { 
     printf("Type \"pass\": "); 
     fgets(inp, sizeof inp, stdin); /* gets is deprecated, use fgets */ 
    } while (strcmp(inp, "pass\n") && msghere("Error!")); 
    msghere("Right Answer!"); 
    getch(); 
    return 0; 
} 

編輯:

爲什麼會出現\n傳球后在while((strcmp(inp, "pass\n") && msghere("Error!"))

要導致fgets提出額外\n在字符串的結尾,您可以使用跳過這一新行:

if (fgets(inp, sizeof inp, stdin) != 0) 
{ 
    size_t len = strlen(inp); 

    if (len > 0 && inp[len - 1] == '\n') 
     inp[len - 1] = '\0'; 
    /* ... */ 
} 

看來你是用的Turbo C或舊的編譯器,用現代的編譯器(如: MinGW的),此外還有:

  • 沒有必要初始化inp
  • 沒有必要memset在每次迭代
  • 函數必須返回某種類型(在這種情況下int)或void
  • const限定符顯式聲明一個數據對象作爲無法更改的內容,請使用它來幫助編譯器構建更好的代碼。
  • 使用int main(void)而不是void main()
0

如果發現string1(或其前n個字節)分別小於,匹配或大於string2,則strcmp()函數返回小於,等於或大於零的整數。

因此你在while循環retuns非零value.so呼叫的strcmp, 下一個條件被評估,即,調用函數(msghere)。該函數執行,打印結果並返回零,這使條件在while循環中爲false。

現在,你知道該怎麼做。