将字符"number"转换为真正的整数

Converting a char "number" into a real int

本文关键字:整数 转换 字符 number      更新时间:2023-10-16

我想要获取用户(数学表达式)的输入并将其压入堆栈。然后我想通过一些规则来运行它,问它是一个'(',一个数字,还是一个运算符'+'。我的问题是,到目前为止,我不知道如何告诉,特别是在while循环的第一个if语句内陈述,如果一个字符"实际上"是一个数字。有什么建议吗?

#include <stack>
int main()
{
    std::stack<char> myStack;    // initializing the stack
    char line[40]; 
    cin.getline(line, 40);       // this and the proceeding line get the input
    for (int i = 0; i < 40; i++)
        myStack.push(line[i]);   //pushing all of the char onto the stack.
    while (!myStack.empty()) {
        if (myStack item = a number) {
        // ^ this is where it doesn't compile.
        //   I need to figure out how to find out if a char is a number
            cout << item << endl;
        }
        else if (myStack.empty()) {
            myStack.push(item);
        }
    }
}

c++中有一个函数叫做isdigit,它检查一个字符是否是十进制数字

if(isdigit(your_char)) //Then it's a number

使用isdigit函数:

isdigit(x)

标准库中有一个名为isdigit()的函数可以为您回答这个问题。

然而,这并没有什么神奇之处。在ASCII中,数字在48-57范围内仅表示chars, 48表示'0', 57表示'9'
char isdigit(char d) {
    return (d >= 48) && (d <= 57);
}

根据您的问题,如果您想要查找一个字符是否是数字。请将其转换为int并检查它是否在ascii值48和57之间,两者都包括在内。

bool CheckIfNum(char chartToCheck)
{
    int aciiOfChar = (int) charToCheck;
    if (asciiOfChar >= 48 && asciiOfChar <= 57)
        return true;
    return false;
}

还可以使用std::isdigit函数