isdigit无法正常工作

编程入门 行业动态 更新时间:2024-10-24 02:23:14
本文介绍了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()); } } }

推荐答案

isdigit 在您的区域设置中使用单个字符的值 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无法正常工作

本文发布于:2023-05-31 10:05:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/389564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法正常   工作   isdigit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!