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

ฟังก์ชัน printf(), sprintf() และ fprintf() ใน C

printf()

พิมพ์ข้อความและค่าตัวแปรไปยังสแตนดาร์ดเอาต์พุต (stdout)

รูปแบบไวยากรณ์

printf(const char *str, ...);

ตัวอย่าง

#include <stdio.h>
int main() {
    int a = 24;
    printf("Welcome! \n");
    printf("The value of a : %d", a);
    getchar();
    return 0;
}

ผลลัพธ์

Welcome!
The value of a : 24

sprintf()

จัดรูปแบบและเก็บข้อความลงในบัฟเฟอร์ตัวอักษร (char buffer) ไม่ได้พิมพ์ออกหน้าจอ

รูปแบบไวยากรณ์

int sprintf(char *str, const char *string, ...);

ตัวอย่าง

#include <stdio.h>
int main() {
    char buf[20];
    int x = 15, y = 25, z;
    z = x + y;
    sprintf(buf, "Sum of values : %d", z);
    printf("%s", buf);
    return 0;
}

ผลลัพธ์

Sum of values : 40

fprintf()

เขียนและจัดรูปแบบข้อมูลออกสตรีม (เช่น ไฟล์) ไม่ใช่พิมพ์ที่คอนโซล

รูปแบบไวยากรณ์

int fprintf(FILE *fptr, const char *str, ...);

ตัวอย่าง

#include <stdio.h>
int main() {
    int i, x = 4;
    char s[20];
    FILE *f = fopen("new.txt", "w");
    if (f == NULL) {
        printf("Could not open file");
        return 0;
    }
    for (i = 0; i < x; i++) {
        puts("Enter text");
        gets(s);
        fprintf(f, "%d.%s\n", i, s);
    }
    fclose(f);
    return 0;
}

ผลลัพธ์

Enter text Hello world!
Enter text Demo

ไฟล์ new.txt จะมีเนื้อหา:

0,Hello world!
1,Demo