C++ 如何一次性获取用户输入并判断是否为数字?

#include "stdafx.h"


#include <iostream>
using namespace std;
bool isNumber(char *str)
{
    
    char *p = str;
    if (*p == '0' && *(p+1) != '\0')   //防止输入第一个为0后面跟数字 例如:03 ...
    {
        cout << "对不起,格式错误!!!" << endl;
        return false;
    } 
    else if (*p < '0' || *p > '9')    // 确定是数字
    {
        cout << "对不起,格式错误!!!" << endl;
        return false;
    }
    else
    {
        return true;
    }
}
void main()
{
    cout << "您好,请输入数字!" << endl;
    char c;
    cin >> c;
    char *pt = &c;

    if (isNumber(pt))

    {

            cout << "您好,您输入的是数字!"; 

}

    else

{

            cout << "对不起,您输入的不是数字,请重新输入!"; }

            getchar();

}


==============================================================

#include "stdafx.h"


#include <iostream>
using namespace std;
bool isNumber(char *str)
{
    bool res = true;
    char *p = str;
    int nLen = 20;
    while ( nLen > 0)
    {   
        if (*p == '\0' && nLen < 20)
        {
            return true;
        }
        if (*p == '0' && *(p + 1) != '\0')   //防止输入第一个为0后面跟数字 例如:03 ...
        {
            //cout << "对不起,格式错误!!!" << endl;
            return false;
        }
        else if (*p < '0' || *p > '9')    // 确定是数字
        {
            //cout << "对不起,格式错误!!!" << endl;
            return false;
        }
        else
        {
            p++;
        }
        nLen--;
    }
    return res;
    
}
void main()
{  
    while (true)
    {
        cout << "您好,请输入数字!" << endl;
        char c[20] = { 0 };
        cin >> c;
        //cin.clear();  清空缓存
        //cin.sync();
        char *pt = c;

        if (isNumber(pt))
        {
            cout << "您好,您输入的是数字!" << c << endl;
        }
        else

        {
            cout << "对不起,您输入的不是数字,请重新输入!";
        }
        getchar();
    }
    
}

posted @ 2023-04-23 21:15  Maguyusi  阅读(42)  评论(0)    收藏  举报  来源