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

Input/Output ของ String ในภาษา C: scanf, printf, gets, puts

String คืออาร์เรย์ของตัวอักษร (character array)

Input/Output พื้นฐาน

  • scanf("%s", str) - รับ string (ไม่รับ space)
  • printf("%s", str) - แสดง string
  • gets(str) - รับ string (รับ space ได้) ไม่แนะนำใช้ (unsafe)
  • puts(str) - แสดง string + newline อัตโนมัติ

โปรแกรมที่ 1: ใช้ scanf/printf

#include <stdio.h>
main() {
    char a[30];
    printf("enter your name: ");
    scanf("%s", a);
    printf("your name is %s", a);
}

ผลลัพธ์

Enter your name: Lucky
Your name is Lucky

หมายเหตุ: scanf ไม่รับ space, ใส่ & ไม่ต้อง (array name คือ address), \0 ใส่อัตโนมัติ

โปรแกรมที่ 2: ใช้ gets/puts

#include <stdio.h>
main() {
    char a[30];
    printf("enter your name: ");
    gets(a);
    printf("Your name is: ");
    puts(a);
}

ผลลัพธ์

Enter your name: Lucky Lol
Your name is Lucky Lol

หมายเหตุ: gets รับ space ได้ แต่ไม่ปลอดภัย (buffer overflow) ควรใช้ fgets() แทน