Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การล้าง Input Buffer ใน C/C++

fflush(stdin) ใช้ล้าง Output Buffer แต่บาง Compiler รองรับล้าง Input Buffer ด้วย (Non-standard) ส่งคืน 0 หากสำเร็จ มิฉะนั้น EOF

รูปแบบ

int fflush(FILE *stream);

ตัวอย่างโค้ด

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

int main() {
    char s[20];
    printf("Enter the string : \n");
    scanf("%s", s);
    printf("The entered string : %s", s);
    fflush(stdin); // Non-standard, อาจไม่ทำงานบนบางระบบ
    return 0;
}

ผลลัพธ์

Enter the string : helloworld
The entered string : helloworld

วิธีมาตรฐานและปลอดภัยกว่า

C: ล้าง Input Buffer ก่อนอ่านบรรทัดใหม่

int c;
while ((c = getchar()) != '\n' && c != EOF); // ล้างจนเจอ newline

C++: ใช้ cin.ignore()

#include <iostream>
#include <limits>

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

หลีกเลี่ยง gets() ใช้ fgets() หรือ std::getline() แทน

gets() ถูก Deprecated และลบออกจาก C11 (Unsafe - Buffer Overflow)