将字符"number"转换为真正的整数
Converting a char "number" into a real int
我想要获取用户(数学表达式)的输入并将其压入堆栈。然后我想通过一些规则来运行它,问它是一个'(',一个数字,还是一个运算符'+'。我的问题是,到目前为止,我不知道如何告诉,特别是在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()
的函数可以为您回答这个问题。
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函数
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 如何在C++中将整数转换为其数字数组
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 将最小值整数转换为无符号长整型
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 将74位整数转换为以31为底的整数
- 独立于实现的浮点/整数转换
- 以最少的步骤将给定整数转换为另一个整数
- 浮点到整数转换出错(即使浮点数已经是整数)
- 了解双精度转换与整数转换中的整数与截断关系
- 禁止具有精度损失的整数转换
- 将任意整数转换为 void*
- 将 32 位大端有符号整数转换为有符号小端整数
- char a[0] 使用 itoa() 将整数转换为字符串的目的
- 使用函数时从整数转换为字符串
- 尝试从整数转换为字符串的月份
- 如何在C++中将整数转换为字节,以便 Unity 在通过 UDP 传输后能够理解它们
- 如何将 Q 格式的整数转换为浮点数(反之亦然)
- 如何避免字符串到整数转换情况下的无效参数异常