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

fgets() และ gets() ใน C

fgets()

อ่านสตริงจนกว่าจะเจอ newline ตรวจสอบ array bound ปลอดภัยกว่า gets()

ไวยากรณ์: char *fgets(char *string, int value, FILE *stream)

string: pointer array char, value: จำนวนตัวอักษรสูงสุด, stream: file pointer (เช่น stdin)

ตัวอย่าง fgets()

#include <stdio.h>
#define FUNC 8
int main() {
    char b[FUNC];
    fgets(b, FUNC, stdin);
    printf("The string is: %s\n", b);
    return 0;
}

ผลลัพธ์

Input: Hello World!
The string is: Hello W

อ่านได้แค่ 7 ตัวอักษร + null (FUNC=8) ตัด "Hello W"

gets()

อ่านสตริงจาก standard input ไม่ตรวจสอบ array bound ไม่ปลอดภัย (deprecated)

ไวยากรณ์: char *gets(char *string);

ตัวอย่าง gets()

#include <stdio.h>
#include <string.h>
int main() {
    char s[100];
    int i;
    printf("\nEnter a string: ");
    gets(s);
    for(i = 0; s[i] != '\0'; i++) {
        if(s[i] >= 'a' && s[i] <= 'z')
            s[i] = s[i] - 32; // to uppercase
    }
    printf("\nString in Upper Case = %s", s);
    return 0;
}

ผลลัพธ์

Enter a string: hello world!
String in Upper Case = HELLO WORLD!

gets() อ่านทั้งบรรทัด แล้วแปลงเป็นพิมพ์ใหญ่

ข้อควรระวัง: gets() ไม่ปลอดภัย ควรใช้ fgets() แทน