判断输入的是否是整数c++
时间: 2023-09-27 12:12:00 浏览: 105
可以通过以下方法判断输入是否是整数:
```cpp
#include <iostream>
#include <string>
#include <regex>
bool isInteger(const std::string& input) {
std::regex integerRegex("^-?\\d+$");
return std::regex_match(input, integerRegex);
}
int main() {
std::string input;
std::cout << "Enter a number: ";
std::cin >> input;
if (isInteger(input)) {
std::cout << "Input is an integer." << std::endl;
} else {
std::cout << "Input is not an integer." << std::endl;
}
return 0;
}
```
这个程序使用了正则表达式来检查输入是否匹配整数的模式。如果输入是一个整数,则返回 true,否则返回 false。
相关问题
c++输入整数判断是否是素数
可以使用以下代码来实现:
```c++
#include <iostream>
using namespace std;
bool isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
int num;
cout << "请输入一个整数:" << endl;
cin >> num;
if (isPrime(num)) {
cout << num << "是素数。" << endl;
} else {
cout << num << "不是素数。" << endl;
}
return 0;
}
```
该程序首先定义了一个 `isPrime` 函数,用于判断一个数是否为素数。接着在 `main` 函数中,先让用户输入一个整数,然后调用 `isPrime` 函数进行判断,并输出判断结果。
c++输入一个整数判断是否为素数
以下是 C++ 的代码实现:
```c++
#include <iostream>
using namespace std;
bool isPrime(int num) {
if (num <= 1) return false; // 1 不是素数
for (int i = 2; i <= sqrt(num); i++) { // 从 2 到根号 num 进行遍历
if (num % i == 0) return false; // 如果存在因子,则不是素数
}
return true;
}
int main() {
int num;
cout << "请输入一个整数:";
cin >> num;
if (isPrime(num)) {
cout << num << " 是素数" << endl;
} else {
cout << num << " 不是素数" << endl;
}
return 0;
}
```
代码中使用 `isPrime` 函数判断一个数是否为素数,如果是素数则返回 `true`,否则返回 `false`。在主函数中,首先输入一个整数,然后调用 `isPrime` 函数进行判断,并输出结果。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)