C++判断字符串有多少数字并输出
时间: 2023-06-13 07:07:03 浏览: 85
可以使用循环遍历字符串中每一个字符,然后判断该字符是否是数字。如果是数字,则计数器加一。最后输出计数器的值即可。
以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
int count = 0;
cout << "请输入字符串:";
getline(cin, str);
for (int i = 0; i < str.length(); i++) {
if (isdigit(str[i])) {
count++;
}
}
cout << "字符串中包含 " << count << " 个数字。" << endl;
return 0;
}
```
在上面的代码中,使用了 `isdigit()` 函数来判断一个字符是否是数字。如果是数字,则返回一个非零值,否则返回零。
相关问题
C++ 判断字符串是否为数字
可以使用 `std::isdigit()` 函数来判断一个字符是否为数字,结合循环遍历字符串的每个字符即可判断整个字符串是否为数字。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
bool isNumber(const std::string& str) {
for (char c : str) {
if (!std::isdigit(c)) {
return false;
}
}
return true;
}
int main() {
std::string str1 = "123";
std::string str2 = "abc";
std::cout << str1 << " is number? " << isNumber(str1) << std::endl;
std::cout << str2 << " is number? " << isNumber(str2) << std::endl;
return 0;
}
```
输出结果为:
```
123 is number? 1
abc is number? 0
```
在上面的代码中,`isNumber()` 函数接受一个 `std::string` 类型的参数,循环遍历字符串中的每个字符,并使用 `std::isdigit()` 函数来判断字符是否为数字。如果存在任何一个非数字字符,则返回 `false`,否则返回 `true`。在 `main()` 函数中测试了两个字符串,一个是数字字符串,一个是非数字字符串。
c++判断字符串是否为数字
您可以使用isdigit()函数来判断一个字符串是否为数字。isdigit()函数是C++标准库中的一个字符处理函数,它的作用是判断一个字符是否为数字字符。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
bool isNumber(const string& str) {
for (char c : str) {
if (!isdigit(c)) {
return false;
}
}
return true;
}
int main() {
string str1 = "12345";
string str2 = "abc123";
if (isNumber(str1)) {
cout << str1 << " is a number." << endl;
} else {
cout << str1 << " is not a number." << endl;
}
if (isNumber(str2)) {
cout << str2 << " is a number." << endl;
} else {
cout << str2 << " is not a number." << endl;
}
return 0;
}
```
在这个示例代码中,我们定义了一个isNumber()函数,它接受一个字符串作为参数,并使用isdigit()函数来判断字符串中的每个字符是否为数字字符。如果字符串中的所有字符都是数字字符,则返回true;否则返回false。在main()函数中,我们分别测试了一个包含数字的字符串和一个包含非数字的字符串。运行上述代码,输出结果如下:
```
12345 is a number.
abc123 is not a number.
```
阅读全文
相关推荐
















