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

ปัญหาของ scanf() เมื่อมี fgets()/gets()/scanf() ตามหลังในภาษา C

ปัญหา: scanf() ตามด้วย fgets()/gets()/scanf() จะทำงานอย่างไร

fgets()/gets() ตามหลัง scanf()

#include <stdio.h>

int main() {
    int x;
    char str[100];
    scanf("%d", &x);
    fgets(str, 100, stdin);
    printf("x = %d, str = %s", x, str);
    return 0;
}

เอาต์พุต

Input: 30 [Enter] String
Output: x = 30, str =

คำอธิบาย: fgets()/gets() รับอินพุตสตริง เมื่อกด Enter หลังตัวเลข fgets() จะอ่าน newline (\n) ที่เหลืออยู่ใน buffer แทนสตริงที่ต้องการ

scanf() ตามหลัง scanf()

ใช้ลูปเพื่อรับ scanf() ซ้ำๆ

#include <stdio.h>

int main() {
    int a;
    printf("enter q to quit");
    do {
        printf("\nenter a character and q to exit");
        scanf("%c", &a);
        printf("%c\n", a);
    } while (a != 'q');
    return 0;
}

เอาต์พุต

Input: a b q
Output: 
enter q to quit
enter a character and q to exit
a
a
enter a character and q to exit

enter a character and q to exit
b
b
enter a character and q to exit

enter a character and q to exit
q

คำอธิบาย: scanf() ทิ้ง newline ไว้ใน buffer ถูกอ่านโดย scanf() ถัดไป แก้ไข: ใช้ scanf("%c\n") หรือ ใช้ getchar() / scanf() เพิ่มเพื่ออ่าน newline ที่เหลือ