本文介绍了isdigit无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过遍历整个字符串并输出整数来测试字符串是否包含一个整数。我的方法包括将字符串转换为c-string, atoi c-string,然后测试是否使用 isdigit 功能。由于一些未知的原因, isdigit 函数返回false,尽管它遇到一个整数。

I am trying to test if a string contains an integer by iterating through the entire string and outputting the integer. My method involves converting the string to c-string , atoi the c-string and then testing if its an integer using isdigit function. For some unknown reason, isdigit function is returning false though it encounters a integer.

我需要帮助解决这个问题

I need help resolving this issue

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

int main()
{
    string p = "[ab, e2cd]";

    for (int k = 0; k < p.length(); k++)
    {
        if (isdigit(atoi(p.substr(k,1).c_str())) == true) //testing done here
        {
            cout << atoi(p.substr(k, 1).c_str());
        }
    }
}


推荐答案

在您的区域设置中使用单个字符的值 int 。从 char 传递一个 unsigned char cast可以,转换到 int 做它的事情。由于 string 包含 chars ,您可以使用这样的元素:

isdigit takes an int with the value of a single character in your locale. It is OK to pass it an unsigned char cast from a char, and let the conversion to int do its thing. Since string contains chars, you can use it's elements like this:

if ( static_cast<unsigned char>(isdigit(p[k])) ) { ....

这篇关于isdigit无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 20:52