วิธีหนึ่งคือใช้ isdigit() ตรวจสอบทุกตัวอักษรในสตริง
ตัวอย่างโค้ด
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
int main() {
char str[] = "3257fg";
for (int i = 0; i < strlen(str); i++) {
if (isdigit(str[i]))
cout << "The string contains int\n";
else
cout << "The string does not contain int\n";
}
return 0;
}
ผลลัพธ์
The string contains int
The string contains int
The string contains int
The string contains int
The string does not contain int
The string does not contain int
วิธีอื่นที่ดีกว่า
สำหรับตรวจสอบสตริงทั้งหมดว่าเป็น int ใช้ strtol() หรือ stoi() (C++) พร้อมตรวจสอบ end pointer:
// C++ แบบสมัยใหม่
#include <string>
bool isInteger(const std::string& s) {
if (s.empty()) return false;
size_t pos;
try {
std::stoi(s, &pos);
return pos == s.size();
} catch (...) {
return false;
}
}
วิธีนี้ตรวจสอบทั้งสตริงครั้งเดียว ไม่ใช่ตัวอักษรทีละตัว