C++输入一行字符,以‘#结尾’,最多10个,之后再输入一个字符,在输入的一行字符中查找后输入的那个字符, 输出该字符在之前输入的字符中出现的次数,没有则输出0.
时间: 2023-12-11 11:05:04 浏览: 36
以下是实现该功能的 C++ 代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[11]; // 存储输入的一行字符,最多10个
char ch; // 存储要查找的字符
int count = 0; // 计数器,记录要查找的字符在输入的字符中出现的次数
cin.getline(str, 11, '#'); // 输入一行字符,以 # 结尾
cin >> ch; // 再输入一个字符,即要查找的字符
// 遍历输入的字符,查找要查找的字符出现的次数
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == ch)
{
count++;
}
}
// 输出结果
cout << count << endl;
return 0;
}
```
注意,本题目要求输入的一行字符最多只能有 10 个,因此在定义字符数组时,大小应该为 11,以便存储最后的结尾符 #。
同时,使用 `cin.getline()` 函数读取一行字符时,第二个参数应该指定数组大小,以防止输入字符过多,导致数组越界。在本题目中,应该指定为 11。
相关问题
C++输入一行大写英文字符(最多30个),以#号结尾,按照ASCII码的值,从小到大,输出每种字符出现的次数。
以下是C++的代码实现:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int count[128] = {0}; // 用一个数组记录每个字符出现的次数,ASCII码共有128个字符
char str[31]; // 输入的字符串最大长度为30,加上结尾的#号,总长度为31
cin.getline(str, 31, '#'); // 输入一行字符,以#号结尾
int len = strlen(str);
for (int i = 0; i < len; i++) {
count[(int)str[i]]++; // 统计每个字符出现的次数
}
for (int i = 0; i < 128; i++) {
if (count[i] > 0) { // 如果该字符出现过,则输出它的ASCII码和出现次数
cout << (char)i << " " << count[i] << endl;
}
}
return 0;
}
```
这个程序利用了一个长度为128的数组 `count` 来记录每个字符出现的次数,数组下标对应字符的 ASCII 码。输入的字符串通过 `cin.getline` 函数读入,读到 # 号为止。接下来循环遍历字符串中的每个字符,将其对应的 `count` 数组元素加一。最后再循环一遍 `count` 数组,输出出现次数不为零的字符及其出现次数。
在c++输入一个字符串,编程统计其单词个数及字母个数
好的,下面是代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
int wordCount = 0, letterCount = 0;
cout << "请输入一个字符串:" << endl;
getline(cin, str);
for (int i = 0; i < str.length(); i++) {
// 判断是否为字母
if (isalpha(str[i])) {
letterCount++;
// 判断是否为单词的结尾
if (i == str.length() - 1 || str[i + 1] == ' ') {
wordCount++;
}
}
}
cout << "单词个数:" << wordCount << endl;
cout << "字母个数:" << letterCount << endl;
return 0;
}
```
这里使用了 `isalpha()` 函数判断是否为字母,使用了 `getline()` 函数输入一行字符串。遍历字符串时,如果遇到字母,就增加字母计数器,同时判断是否为单词的结尾,如果是,则增加单词计数器。最后输出单词个数和字母个数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)