c++ 判断字符串中是否全为数字
时间: 2023-09-22 17:08:18 浏览: 115
可以使用C++自带的函数`isdigit()`来判断字符串中是否全为数字。具体实现代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
bool is_numeric(string str) {
for (int i = 0; i < str.length(); i++) {
if (!isdigit(str[i])) {
return false;
}
}
return true;
}
int main() {
string str = "123456";
if (is_numeric(str)) {
cout << "字符串 " << str << " 中全为数字!" << endl;
} else {
cout << "字符串 " << str << " 中不全为数字!" << endl;
}
return 0;
}
```
在上面的代码中,我们定义了一个`is_numeric()`函数,它接受一个字符串参数`str`,并返回一个布尔值。在函数中,我们使用了`isdigit()`函数来判断`str`中的每一个字符是否为数字。如果存在非数字字符,则返回false,否则返回true。最后在主函数中,我们测试了一个字符串是否全为数字,并输出结果。
相关问题
c++ 判断字符串中是否有特定字符串
你可以使用 C++ 的字符串查找函数来判断一个字符串中是否包含特定的子字符串。一个常用的函数是 `find()`,它返回子字符串在原字符串中的位置,如果找不到则返回 `string::npos`。以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string subStr = "World";
size_t found = str.find(subStr);
if (found != std::string::npos) {
std::cout << "子字符串找到在位置:" << found << std::endl;
} else {
std::cout << "子字符串未找到" << std::endl;
}
return 0;
}
```
该代码将输出 "子字符串找到在位置:7",因为 "World" 存在于原字符串中,并且其起始位置为 7。如果你想判断一个字符串是否包含特定的子字符串,你可以使用类似的方法。
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.
```