C++ 程序检查输入是整数还是字符串
c++server side programmingprogramming更新于 2024/10/10 14:11:00
用户输入一个数字,任务是检查给定的输入是整数还是字符串。
整数可以是 0 -9 之间的任意数字组合,字符串可以是 0 和 9 之外的任意组合。
示例
输入:123 输出:123 是一个整数 输入:教程点 输出:教程点是一个字符串
下面使用的方法如下 −
- 输入数据。
- 应用 isdigit() 函数检查给定的输入是否为数字字符。此函数将单个参数作为整数,并返回 int 类型的值。
- 打印结果输出。
算法
开始 步骤 1->声明函数以检查数字或字符串 bool check_number(string str) Loop For int i = 0 and i < str.length() and i++ If (isdigit(str[i]) == false) return false End End 返回 true 步骤 2->Int main() 设置字符串 str = "sunidhi" IF (check_number(str)) 打印 " 是一个整数" End Else 打印 " 是一个字符串" End 设置字符串 str1 = "1234" IF (check_number(str1)) 打印"是整数" End Else 打印"是字符串" End Stop
示例
#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"; }
输出
sunidhi is a string 1234 is an integer