Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตรวจสอบ Input เป็นตัวเลขใน C++: isdigit และ string validation

การตรวจสอบว่า 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

เปรียบเทียบวิธีการ

วิธีPerformanceFeaturesC++ Version
Manual LoopFastDigits OnlyC++98
all_of + LambdaFastDigits Only, ReadableC++11
stoi/stod + ExceptionSlow (Exception)Full Number ParsingC++11
from_charsFastest, No ExceptionInteger/Float, No LocaleC++17

สรุป

  • Digits Only (0-9): ใช้ all_of + isdigit (Simple, Fast)
  • Full Number Parsing: ใช้ std::from_chars (C++17, Best Performance) หรือ stod (Legacy)
  • ระวัง isdigit กับ char Signed -> Cast เป็น unsigned char เสมอ
  • Empty String ควรคืน false