स्ट्रिंग इनपुट को वैलिडेट करने के लिए कि क्या यह केवल अंकों (0-9) से बना है, प्रत्येक कैरेक्टर को isdigit() से जांचें।
C++ दृष्टिकोण (std::string)
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool isNumeric(const string &str) {
if (str.empty()) return false;
for (char ch : str) {
if (!isdigit(static_cast<unsigned char>(ch)))
return false;
}
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isNumeric(str))
cout << "This is a Number\n";
else
cout << "This is not a number\n";
return 0;
}
आउटपुट
Enter a string: 5687 This is a Number Enter a string: 584asS This is not a number
C दृष्टिकोण (char ऐरे)
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isNumeric(const char *str) {
if (!str || *str == '\0') return false;
while (*str) {
if (!isdigit((unsigned char)*str))
return false;
str++;
}
return true;
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%99s", str);
if (isNumeric(str))
printf("This is a Number\n");
else
printf("This is not a number\n");
return 0;
}
उन्नत: चिह्न और ओवरफ्लो हैंडलिंग
// strtol के साथ पूर्ण इंटीजर पार्सिंग
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
bool parseInt(const char *str, long *out) {
char *endptr;
errno = 0;
long val = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0') return false; // कोई अंक नहीं या अतिरिक्त कैरेक्टर्स
if (errno == ERANGE) return false; // ओवरफ्लो
*out = val;
return true;
}
मुख्य बिंदु
isdigit()के लिए<cctype>/<ctype.h>शामिल करें।unsigned charकास्टisdigitके लिए अनडिफाइंड बिहेवियर से बचाता है।- उत्पादन कोड के लिए
strtol/strtollअधिक मजबूत हैं।