可以使用isdigit()函数来判断字符串中的每个字符是否都是数字,如果是数字则返回true,否则返回false。以下是一个示例代码:

#include <iostream>
#include <cstring>
using namespace std;

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

int main() {
    string str;
    cout << "请输入一个字符串:";
    cin >> str;
    
    if (isAllDigits(str)) {
        cout << "该字符串全是数字" << endl;
    } else {
        cout << "该字符串不全是数字" << endl;
    }
    
    return 0;
}

在上述代码中,isAllDigits()函数接受一个字符串作为参数,然后使用一个for循环遍历字符串中的每个字符,通过isdigit()函数判断是否为数字。如果存在非数字字符,则返回false,否则返回true。

在main()函数中,首先提示用户输入一个字符串,然后调用isAllDigits()函数进行判断,并输出结果

判断字符串是否全是数字的C++代码

原文地址: https://www.cveoy.top/t/topic/iahn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录