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

วิธีตรวจสอบว่าอินพุตเป็นจำนวนเต็มหรือไม่ใน C/C++

บทความนี้แสดงวิธีตรวจสอบว่าสตริงที่รับเข้ามาเป็นตัวเลข (0-9) เท่านั้นหรือไม่ วิธีแก้คือวนลูปตรวจสอบตัวอักษรแต่ละตัวด้วยฟังก์ชัน isdigit()

ตัวอย่าง

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

bool isNumeric(string str) {
    for (int i = 0; i < str.length(); i++)
        if (isdigit(str[i]) == false)
            return false;
    return true;
}

int main() {
    string str;
    cout << "Enter a string: ";
    cin >> str;
    if (isNumeric(str))
        cout << "This is a Number" << endl;
    else
        cout << "This is not a number";
    return 0;
}

ผลลัพธ์

Enter a string: 5687
This is a Number
Enter a string: 584asS
This is not a number