scanf_s獲取參數,清空緩沖區,判斷是否讀取成功


#include<stdio.h>

int main() {
    char str[5];
    while (1) {
        printf("Please input:\n");
        int rtn=scanf_s("%s", str, 5);
        if (rtn == 0) {
            printf("scanf_s failure!\n");
            rewind(stdin);//windows平台下清空字符緩沖區。fflush(stdin)不建議使用,好像沒有效果
        }
        else {
            printf("Your input:%s\n", str);
        }
        printf("%d-----------------------------------------------\n", rtn);
    }
    return 0;
}

如果是使用scanf注意內存越界,改變了其他變量的值。注意限制字符讀取的長度。

以下是運行結果:

Please input:
123456789
scanf_s failure!
0-----------------------------------------------
Please input:
1
Your input:1
1-----------------------------------------------
Please input:
11
Your input:11
1-----------------------------------------------
Please input:
111
Your input:111
1-----------------------------------------------
Please input:
1111
Your input:1111
1-----------------------------------------------
Please input:
11111
scanf_s failure!
0-----------------------------------------------
Please input:
111111
scanf_s failure!
0-----------------------------------------------
Please input:

 如果清空緩沖區的那一行代碼被注釋,如下:

#include<stdio.h>

int main() {
    char str[5];
    while (1) {
        printf("Please input:\n");
        int rtn=scanf_s("%s", str, 5);
        if (rtn == 0) {
            printf("scanf_s failure!\n");
            //rewind(stdin);//windows平台下清空字符緩沖區。fflush(stdin)不建議使用,好像沒有效果
        }
        else {
            printf("Your input:%s\n", str);
        }
        printf("%d-----------------------------------------------\n", rtn);
    }
    return 0;
}

則運行結果變成了

Please input:
123456789
scanf_s failure!
0-----------------------------------------------
Please input:
Your input:6789
1-----------------------------------------------
Please input:
111111111111111111
scanf_s failure!
0-----------------------------------------------
Please input:
scanf_s failure!
0-----------------------------------------------
Please input:
scanf_s failure!
0-----------------------------------------------
Please input:
Your input:111
1-----------------------------------------------
Please input:

最后一定要注意scanf_s的后面的長度雖然是5,但是只能接收4個字符,不然就會接收鍵盤輸入失敗。

另外,scanf_s的第二個參數是變量的地址(數組名也是變量的地址),第三個參數是(unsigned int)的類型(也可以直接使用正整數)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM