ปัญหา
เกิดข้อผิดพลาดทั่วไปขณะอ่านสตริงและข้อมูลตัวเลขโดยใช้ฟังก์ชัน scanf() ในภาษา C
วิธีแก้ปัญหา
scanf() ฟังก์ชัน ใช้เพื่ออ่านอินพุตที่จัดรูปแบบจาก stdin ในภาษา C คืนค่าจำนวนอักขระทั้งหมดที่เขียนไว้ มิฉะนั้นจะคืนค่าเป็นค่าลบ
โดยทั่วไปในกรณีของฟังก์ชัน scanf() ขณะอ่านค่าสตริงหลังจำนวนเต็มจากผู้ใช้ เราได้รับข้อผิดพลาดบ่อยครั้ง
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C ซึ่งอ่านหมายเลขม้วน (ค่าจำนวนเต็ม) และชื่อนักเรียน -
#include <stdio.h>
struct student {
char name[10];
int roll;
} s;
int main(){
printf("Enter information of students:\n");
printf("\nEnter roll number: ");
scanf("%d", &s.roll);
printf("\nEnter name: ");
gets(s.name);
printf("\nDisplaying Information of students:\n");
printf("\nRoll number: %d\t", s.roll);
printf("\nname:%s\t", s.name);
return 0;
} ผลลัพธ์
ในตัวอย่างข้างต้น คอมไพเลอร์อ่าน roll no:หลังจากนั้นคอมไพเลอร์จะไม่สามารถอ่านชื่อและย้ายไปยังคำสั่งถัดไปซึ่งก็คือ printf("Roll Number is:%d\t, s.roll);
and the output is "Roll number: 3 name: "
นี่เป็นข้อผิดพลาดทั่วไปที่เกิดขึ้นขณะอ่านสตริงและข้อมูลตัวเลขโดยใช้ฟังก์ชัน scanf() ในภาษา C
Enter information of students: Enter roll number: 3 Enter name: //error Displaying Information of students: Roll number: 3 name: //error