เราจะมาดูวิธีการตรวจสอบว่าอินพุตที่กำหนดเป็นสตริงตัวเลขหรือสตริงปกติได้อย่างไร สตริงตัวเลขจะเก็บอักขระทั้งหมดที่อยู่ในช่วง 0 – 9 วิธีแก้ปัญหานั้นง่ายมาก เราจะพิจารณาแต่ละอักขระทีละตัว และตรวจสอบว่าเป็นตัวเลขหรือไม่ หากเป็นตัวเลข ให้ชี้ไปที่ถัดไป ไม่เช่นนั้นให้คืนค่าเท็จ
ตัวอย่าง
#include <iostream>
using namespace std;
bool isNumeric(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false; //when one non numeric value is found, 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";
} ผลลัพธ์
Enter a string: 5687 This is a Number
ผลลัพธ์
Enter a string: 584asS This is not a number