用c++用指针编写程序,当从键盘输入一个字符串后要求统计这个字符串中数字字符的个数(用子函数, 参数是字符指针)
时间: 2024-02-27 13:55:36 浏览: 21
好的,我理解了你的问题。以下是 C++ 代码实现:
```c++
#include <iostream>
using namespace std;
int countDigits(char* str) {
int count = 0;
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
cout << "请输入一个字符串: ";
cin.getline(str, 100);
int count = countDigits(str);
cout << "数字字符的个数为: " << count << endl;
return 0;
}
```
在上面的代码中,我们定义了一个 `countDigits` 函数,它的参数是一个字符指针,用于统计其中数字字符的个数。在 `main` 函数中,我们通过 `cin.getline` 从键盘输入一个字符串,并将其传递给 `countDigits` 函数进行统计。最后,我们输出数字字符的个数。
相关问题
使用c++3.用指针编写程序,当从键盘输入一个字符串后要求:(2)统计这个字符串中数字字符的个数(用子函数, 参数是字符指针)
好的,我来帮您编写这个程序。下面是实现过程:
```cpp
#include <iostream>
using namespace std;
// 统计数字字符个数的子函数
int count_num(char* str)
{
int count = 0;
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
int main()
{
const int MAX_LEN = 100; // 定义字符串最大长度
char str[MAX_LEN]; // 定义字符数组
cout << "请输入一个字符串:" << endl;
cin.getline(str, MAX_LEN); // 输入字符串
int num_count = count_num(str); // 调用子函数统计数字字符个数
cout << "数字字符的个数为:" << num_count << endl;
return 0;
}
```
以上程序中,我们定义了一个名为 `count_num` 的子函数,用于统计字符串中数字字符的个数。在 `main` 函数中,我们先定义了一个字符串数组 `str`,并通过 `cin.getline` 函数从键盘读入一个字符串。然后,我们调用 `count_num` 函数统计字符串中数字字符的个数,并将结果输出。
需要注意的是,在 `count_num` 函数中,我们使用了指针来遍历字符串中的每一个字符,如果该字符是数字字符,则计数器加一。最终,我们返回计数器的值作为统计结果。
用C++语言编写程序:从键盘输入一个字符串(注意:字符串中含有空格),使用字符数组型和字符型指针来实现程序的功能,统计且输出字符串中字母的个数。
以下是使用字符数组型实现的程序:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int MAX_LEN = 100;
char str[MAX_LEN];
cin.getline(str, MAX_LEN);
int count = 0;
for (int i = 0; i < strlen(str); i++) {
if (isalpha(str[i])) {
count++;
}
}
cout << "字母个数:" << count << endl;
return 0;
}
```
以下是使用字符型指针实现的程序:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int MAX_LEN = 100;
char* str = new char[MAX_LEN];
cin.getline(str, MAX_LEN);
int count = 0;
for (int i = 0; i < strlen(str); i++) {
if (isalpha(str[i])) {
count++;
}
}
cout << "字母个数:" << count << endl;
delete[] str;
return 0;
}
```
这两个程序的实现思路基本一致,只是一个使用了字符数组型,一个使用了字符型指针。