3. 用C++编写一个从输入流中读取std::string的函数。如何检查字符串是否只包含数字?编写程序,使用std::isdigit (task1.cpp)检查std::string是否只包含数字。
时间: 2024-05-10 19:15:39 浏览: 89
以下是读取字符串并检查其是否只包含数字的函数实现:
```c++
#include <iostream>
#include <string>
#include <cctype>
bool isNumeric(const std::string& str) {
for (char c : str) {
if (!std::isdigit(c)) {
return false;
}
}
return true;
}
int main() {
std::string input;
std::cout << "Enter a string: ";
std::cin >> input;
if (isNumeric(input)) {
std::cout << "The string only contains digits." << std::endl;
} else {
std::cout << "The string does not only contain digits." << std::endl;
}
return 0;
}
```
该程序会提示用户输入一个字符串,并使用 `isNumeric` 函数检查该字符串是否只包含数字。函数使用 `std::isdigit` 函数来判断每个字符是否为数字。如果字符串中有任何一个非数字字符,则返回 `false`,否则返回 `true`。
阅读全文
相关推荐











