2013-11-26 60 views
0

我剛開始使用C,我在編譯時遇到了一些麻煩。 似乎編譯器經常遇到char錯誤。 請注意,我必須在%c之前放置空格。 現在經過在線研究了一下,我瞭解到,加入後,&標誌幾乎解決了這個問題,但是我完全解決了這個問題,因爲它應該可以正常工作。 我使用Visual Studio 2013 btw。遇到char和scanf_s()的問題

#include <stdio.h> 

void main() 
{ 

    int num; 
    char flag; 
    while (1) 
    { 

    printf("Please enter your no.:"); 
    scanf_s("%d", &num); 

    if (num > -1) 
    { 

     if (num < 10) 
     { 
     printf("Your number is 1 digit.\n"); 
     } 

     else if (num < 100) 
     { 
     printf("Your number is 2 digits.\n"); 
     } 

     else if (num < 1000) 
     { 
     printf("Your number is 3 digits.\n"); 

     } 

     else if (num > 999) 
     { 
     printf("Your number has a lot of digits.\n"); 

     } 
    } 

    else 
    { 
     printf("Please input a correct value.\n"); 

    } 

    printf("Would you like to countinue? y/n \n"); 
    scanf_s(" %c", &flag) 
    // problem 

    if (flag == 'n') 
    { 
     exit(0); 
    } 
    } 

} 

回答

0

您的代碼無效,您必須指定緩衝區大小爲scanf_s()See the documentation

不同於scanfwscanfscanf_swscanf_s需要的緩衝區大小爲類型C,C,S,S,或[的所有輸入參數來指定。以字符爲單位的緩衝區大小作爲附加參數傳遞到緩衝區或變量的指針之後。

這就是爲什麼它的工作原理,如果你添加撥打電話scanf_s(" %c", &flag, 1);

+0

同時也刪除「%c」中的空格,即上面的「%C」。 – VDN

+0

謝謝,這解決了它。不過,我仍然需要在%c之前放置空格。 – omm118

+1

@VDN在這種情況下,需要使用格式化字符串中的空格,以便在while()循環開始時使用scanf_s來讀取num中的stdin中留下的換行符。 –