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

ฟังก์ชัน scanf() และ fscanf() ในภาษา C


ฟังก์ชัน scanf()

ฟังก์ชัน scanf() ใช้สำหรับอ่านข้อมูลนำเข้าแบบจัดรูปแบบ (formatted input) จาก standard input (stdin) ในภาษา C ฟังก์ชันนี้คืนค่าจำนวนรายการที่อ่านสำเร็จ มิฉะนั้นจะคืนค่าลบ

ไวยากรณ์

int scanf(const char *format, ...);

ตัวอย่างการใช้งาน scanf()

#include <stdio.h>

int main() {
    char s[20];
    printf("Enter a string : ");
    scanf("%s", s);
    printf("\nEntered string : %s\n", s);
    return 0;
}

ผลลัพธ์

Enter a string : Peter!
Entered string : Peter!

ฟังก์ชัน fscanf()

ฟังก์ชัน fscanf() ใช้สำหรับอ่านข้อมูลนำเข้าแบบจัดรูปแบบจากสตรีมที่กำหนด (เช่น ไฟล์) ในภาษา C ฟังก์ชันนี้คืนค่าจำนวนรายการที่อ่านสำเร็จ หรือ EOF หากเกิดข้อผิดพลาด

ไวยากรณ์

int fscanf(FILE *stream, const char *format, ...);

ตัวอย่างการใช้งาน fscanf()

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

int main() {
    char str1[10];
    int year;
    FILE *fp;
    
    fp = fopen("file.txt", "w+");
    fputs("This is demo text!", fp);
    rewind(fp);
    fscanf(fp, "%s", str1);
    printf("First word = \n%s\n", str1);
    fclose(fp);
    return 0;
}

ผลลัพธ์

First word = This

ข้อสังเกต: scanf() อ่านจากคีย์บอร์ด (stdin) ส่วน fscanf() อ่านจากไฟล์หรือสตรีมอื่นๆ ทั้งคู่ใช้สเปกฟอร์แมตเหมือนกัน (เช่น %d, %s, %f)