求c语言程序:从键盘输入一行字符,统计有多少个英文单词。 例如,输入:There are 45 students. 输出:3
时间: 2024-05-03 14:22:04 浏览: 14
好的,我可以帮您实现这个功能。以下是 C 语言代码示例:
```c
#include <stdio.h>
int main() {
int count = 0;
char str[100];
printf("请输入一行字符串:\n");
fgets(str, 100, stdin);
int i = 0;
while (str[i]) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
count++;
while (((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) && str[i]) {
i++;
}
}
else {
i++;
}
}
printf("输入字符中英文单词的个数为:%d\n", count);
return 0;
}
```
通过 fgets 函数从标准输入中读取输入的一行字符串,然后遍历这个字符串,判断每个字符是否属于英文字母,如果是,就认为遇到了一个单词,然后往后遍历直到遇到了一个非英文字母的字符,这样就统计出了输入字符串中的英文单词数量。
相关问题
C语言程序:从键盘输入10个字符,将其全部输出到一个磁盘文件“data.dat"中保存起来”
好的,以下是实现该功能的 C 语言程序:
```c
#include <stdio.h>
int main()
{
char str[10];
FILE *fp;
// 打开文件
fp = fopen("data.dat", "w");
// 从键盘输入10个字符
printf("请输入10个字符:\n");
scanf("%s", str);
// 将输入的字符全部输出到文件中
fprintf(fp, "%s", str);
// 关闭文件
fclose(fp);
printf("输入的字符已保存到文件中!\n");
return 0;
}
```
程序的实现过程如下:
1. 定义一个字符数组 `str` 存储从键盘输入的字符;
2. 定义一个文件指针 `fp`,指向待创建的文件 `data.dat`;
3. 使用 `fopen()` 函数创建并打开文件,打开方式为写入("w");
4. 使用 `printf()` 和 `scanf()` 函数从键盘输入10个字符,存储到 `str` 数组中;
5. 使用 `fprintf()` 函数将 `str` 数组中的字符全部输出到打开的文件中;
6. 使用 `fclose()` 函数关闭文件;
7. 输出提示信息,表示输入的字符已保存到文件中;
8. 返回程序执行结果。
希望能够帮助到您!
用C语言写一个程序:从键盘输入字符串,统计字符串中数字字符出现的次数并输出
下面是一个简单的 C 语言程序,可以实现从键盘输入字符串,统计字符串中数字字符出现的次数并输出:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, count = 0;
printf("请输入字符串:");
scanf("%s", str);
for (i = 0; i < strlen(str); i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
printf("字符串中数字字符出现的次数为:%d\n", count);
return 0;
}
```
程序首先声明一个字符数组 `str`,用于存储输入的字符串。然后使用 `scanf` 函数从键盘读入字符串,存储到 `str` 数组中。
接着使用 `for` 循环遍历字符串中的每个字符,如果当前字符是数字字符,则将计数器 `count` 加 1。
最后输出计数器 `count` 的值,即字符串中数字字符出现的次数。
需要注意的是,这个程序只能统计 ASCII 码表中的数字字符,如果字符串中包含其他编码的数字字符,可能无法正确统计。同时,这个程序也没有对字符串长度进行限制,如果输入的字符串过长,可能会导致程序崩溃。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)