ปัญหา
คอมไพเลอร์ไม่อ่านสตริงหลังจากจำนวนเต็มในการเขียนโปรแกรม C? เราจะแก้ปัญหานี้ได้อย่างไร
วิธีแก้ปัญหา
เมื่อคุณป้อนตัวเลขจำนวนเต็มและกด Enter เพื่ออ่านค่าถัดไป คอมไพเลอร์จะเก็บค่า null ไว้ในอักขระตัวแรกของสตริงและอินพุตสตริงจะสิ้นสุดลง เนื่องจาก scanf จะสิ้นสุดเมื่อใดก็ตามที่อ่านอักขระว่าง
จะแก้ไขอย่างไร?
เมื่อเราพยายามอ่านสตริงหรืออักขระหลัง int หรือ float เราควรอ่านอักขระชั่วคราวซึ่งมีอยู่ในบัฟเฟอร์อินพุต
ต่อไปนี้เป็นโปรแกรมที่ไม่มีข้อผิดพลาด -
ตัวอย่าง
#include <stdio.h>
struct student{
char name[10];
int roll;
char temp;
} s;
int main(){
printf("Enter information of students:\n");
printf("\nEnter roll number: ");
scanf("%d", &s.roll);
scanf("%c",&s.temp); //read temporary character
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;
} ผลลัพธ์
Enter information of students: Enter roll number: 3 Enter name: tutorialspoint Displaying Information of students: Roll number: 29806 name:tutorialspoint