บทนำ
รับอินพุตจากผู้ใช้ ต้องการตรวจสอบว่าอินพุตเป็นจำนวนเต็ม (integer) หรือสตริง (string)
- Integer: ตัวเลข 0-9 เท่านั้น
- String: อักขระอื่นๆ ที่ไม่ใช่ 0-9
ตัวอย่าง
- Input: 123 → Output: 123 is an integer
- Input: Tutorials Point → Output: Tutorials Point is a string
แนวคิด
ใช้ฟังก์ชัน isdigit() ตรวจสอบทุกตัวอักษรในสตริง ถ้าทุกตัวเป็นตัวเลข → integer มิฉะนั้น → string
ตัวอย่างโค้ด C++
#include <iostream>
using namespace std;
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main() {
string str = "sunidhi";
if (check_number(str))
cout << str << " is an integer" << endl;
else
cout << str << " is a string" << endl;
string str1 = "1234";
if (check_number(str1))
cout << str1 << " is an integer";
else
cout << str1 << " is a string";
return 0;
}
ผลลัพธ์
sunidhi is a string 1234 is an integer