การตรวจสอบว่า String Input ประกอบด้วยตัวเลข (Digits 0-9) เท่านั้น เป็นงานพื้นฐานใน Input Validation มีหลายวิธีใน C++ ตั้งแต่ Manual Loop ไปจนถึง Library Functions
วิธีที่ 1: Manual Loop + isdigit (Classic)
#include <iostream>
#include <string>
#include <cctype> // isdigit
bool isNumeric(const std::string& str) {
if (str.empty()) return false;
for (char c : str) {
if (!std::isdigit(static_cast<unsigned char>(c)))
return false;
}
return true;
}
Note: Cast เป็น unsigned char ก่อนส่งให้ isdigit เพื่อป้องกัน UB กับ Char สigned negative values
วิธีที่ 2: std::all_of + Lambda (C++11, Expressive)
#include <algorithm>
#include <cctype>
bool isNumeric(const std::string& str) {
return !str.empty() &&
std::all_of(str.begin(), str.end(),
[](char c) { return std::isdigit(static_cast<unsigned char>(c)); });
}
วิธีที่ 3: std::stoi / std::stod + Exception Handling (Convert & Validate)
#include <string>
bool isInteger(const std::string& str) {
try {
size_t pos;
std::stoi(str, &pos);
return pos == str.size(); // ต้อง consume ทั้งสตริง
} catch (...) {
return false;
}
}
วิธีที่ 4: std::from_chars (C++17, Fast, No Exception, No Locale)
#include <charconv> // C++17
#include <string_view>
bool isInteger(const std::string& str) {
int value;
auto result = std::from_chars(str.data(), str.data() + str.size(), value);
return result.ec == std::errc() && result.ptr == str.data() + str.size();
}
ขยาย: รองรับเครื่องหมาย +/-, Decimal Point, Scientific Notation
bool isNumber(const std::string& str) {
// ใช้ std::stod + pos check
try {
size_t pos;
std::stod(str, &pos);
return pos == str.size();
} catch (...) {
return false;
}
}
// รองรับ: "123", "-45", "+3.14", "1e-5", ".5"
ตัวอย่างโปรแกรมสมบูรณ์
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
bool isNumeric(const std::string& str) {
return !str.empty() &&
std::all_of(str.begin(), str.end(),
[](char c) { return std::isdigit(static_cast<unsigned char>(c)); });
}
int main() {
std::string input;
std::cout << "Enter a string: ";
std::cin >> input;
if (isNumeric(input))
std::cout << "This is a Number\n";
else
std::cout << "This is not a number\n";
}
ผลลัพธ์
Enter a string: 5687
This is a Number
Enter a string: 584asS
This is not a number
เปรียบเทียบวิธีการ
| วิธี | Performance | Features | C++ Version |
|---|---|---|---|
| Manual Loop | Fast | Digits Only | C++98 |
| all_of + Lambda | Fast | Digits Only, Readable | C++11 |
| stoi/stod + Exception | Slow (Exception) | Full Number Parsing | C++11 |
| from_chars | Fastest, No Exception | Integer/Float, No Locale | C++17 |
สรุป
- Digits Only (0-9): ใช้
all_of + isdigit(Simple, Fast) - Full Number Parsing: ใช้
std::from_chars(C++17, Best Performance) หรือstod(Legacy) - ระวัง
isdigitกับcharSigned -> Cast เป็นunsigned charเสมอ - Empty String ควรคืน
false