用c++设计一个实现有一行文字要求统计出其中的数字,空格的个数的程序
时间: 2024-03-12 08:48:14 浏览: 13
好的,以下是一个简单的 C++ 程序,可以统计一行文字中的数字和空格的个数:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
int numbers = 0;
int spaces = 0;
cout << "请输入一行文字:" << endl;
getline(cin, line);
for (char c : line) {
if (isdigit(c)) {
numbers++;
}
else if (isspace(c)) {
spaces++;
}
}
cout << "数字个数为:" << numbers << endl;
cout << "空格个数为:" << spaces << endl;
return 0;
}
```
这个程序首先会让用户输入一行文字,然后使用 `getline` 函数将这一行文字读入到一个字符串变量 `line` 中。接下来,程序使用一个 `for` 循环遍历字符串中的每一个字符,如果这个字符是数字,则将 `numbers` 计数器加一;如果这个字符是空格,则将 `spaces` 计数器加一。最后,程序输出数字和空格的个数。
希望这个程序能够帮助到你!
相关问题
C++输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
C++输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数可以使用getchar()函数逐个读取字符,并根据字符的ASCII码值判断其属于哪一类。具体实现可以参考以下代码:
```
#include <iostream>
using namespace std;
int main() {
char c;
int letter = 0, space = 0, number = 0, other = 0;
cout << "请输入一行字符:" << endl;
while ((c = getchar()) && (c != '\n')) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
letter++;
else if (c == ' ')
space++;
else if (c >= '0' && c <= '9')
number++;
else
other++;
}
cout << "英文字母个数为:" << letter << endl;
cout << "空格个数为:" << space << endl;
cout << "数字个数为:" << number << endl;
cout << "其他字符个数为:" << other << endl;
return 0;
}
```
用c++实现输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i;
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入一行字符:");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isspace(str[i])) {
spaces++;
} else if (isdigit(str[i])) {
digits++;
} else {
others++;
}
}
printf("其中英文字母个数:%d\n", letters);
printf("其中空格个数:%d\n", spaces);
printf("其中数字个数:%d\n", digits);
printf("其中其他字符个数:%d\n", others);
return 0;
}