C kiritilgan ma’lumotni tekshirish


ULASHISH

Kiritilgan ma’lumotni tekshirish

Foydalanuvchilar C dasturiga ma’lumot kiritganda kutilmagan narsani yozib qo‘yishlari mumkin. Kiritilgan ma’lumotni tekshirish dastur ishini davom ettirishidan oldin ma’lumot to‘g‘ri ekanligiga ishonch hosil qiladi.

Tekshiruvsiz dasturingiz ishdan chiqishi yoki noto‘g‘ri natija berishi mumkin!

Quyidagi misollarda C tilida foydalanuvchi kiritgan ma’lumot to‘g‘ri ekanligini tekshirishning oddiy usullari ko‘rsatilgan.


Son oralig‘ini tekshirish

Son ruxsat etilgan oraliqda (masalan, 1 dan 5 gacha) ekanligini tekshiring:

Misol

#include <stdio.h> int main() {   int number; // Variable to store the user's number   do {     printf("Choose a number between 1 and 5: ");     scanf("%d", &number); // Read number input     while (getchar() != '\n'); // Clear leftover characters from input buffer   } while (number < 1 || number > 5); // Keep asking until number is between 1 and 5   printf("You chose: %d\n", number); // Print the valid number   return 0; }

Natija namunasi:

Choose a number between 1 and 5: 8
Choose a number between 1 and 5: -2
Choose a number between 1 and 5: 4
You chose: 4

Matnli kiritishni tekshirish

Ism bo‘sh emasligini tekshiring. fgets() funksiyasidan foydalaning va birinchi belgini tekshiring:

Misol

#include <stdio.h> #include <string.h> int main() {   char name[100]; // Buffer to store the user's name   do {     printf("Enter your name: ");     fgets(name, sizeof(name), stdin); // Read input as a string     name[strcspn(name, "\n")] = 0; // Remove the newline character if present   } while (strlen(name) == 0); // Repeat if the input is empty   printf("Hello, %s\n", name); // Greet the user   return 0; }

Natija namunasi:

Enter your name:
Enter your name:
Enter your name: John
Hello, John


Butun son kiritilishini tekshirish

Foydalanuvchi son kiritganiga ishonch hosil qiling. Agar u boshqa narsa (masalan, harf) kiritsa, fgets() va sscanf() yordamida qaytadan so‘rang:

Misol

#include <stdio.h> int main() {   int number;       // Variable to store the user's number   char input[100];  // Buffer to hold user input as a string   printf("Enter a number: ");   // Keep reading input until the user enters a valid integer   while (fgets(input, sizeof(input), stdin)) {     // Try to read an integer from the input string     if (sscanf(input, "%d", &number) == 1) {       break; // Success: break out of the loop     } else {       printf("Invalid input. Try again: "); // If not an integer, ask again     }   }   // Print the valid number entered by the user   printf("You entered: %d\n", number);   return 0; }

Natija namunasi:

Enter a number: AB
Invalid input. Try again: 3.5
Invalid input. Try again: 35
You entered: 35

Maslahat: fgets() va sscanf() haqida batafsil ma’lumotni <stdio.h> kutubxonasi ma’lumotnomamizda o‘qishingiz mumkin.


W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!