用c++输入一串字符,按照每种字符出现的次数输出
时间: 2024-03-08 10:50:16 浏览: 26
好的,以下是一份用 C++ 实现的代码,它可以读入一串字符,然后按照每种字符出现的次数输出:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::string str;
std::getline(std::cin, str);
std::unordered_map<char, int> charCount;
for (char c : str) {
if (charCount.find(c) == charCount.end()) {
charCount[c] = 1;
} else {
charCount[c]++;
}
}
for (const auto& pair : charCount) {
std::cout << "'" << pair.first << "' appeared " << pair.second << " times." << std::endl;
}
return 0;
}
```
这份代码使用了一个 `unordered_map` 来记录每个字符出现的次数,然后遍历这个 `unordered_map` 输出结果。
相关问题
C++编程:输入一个字符串,将其逆序后输出
以下是一种实现方式:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
return 0;
}
```
首先定义一个字符数组 `str` 用于存储输入的字符串,然后使用 `scanf` 函数读取用户输入的字符串。接着使用 `strlen` 函数获取字符串的长度,从字符串末尾开始循环输出每个字符,实现字符串的逆序输出。最后记得输出一个换行符。
输入一个字符串c++
要输入一个字符串c++,有多种方法可以实现。以下是其中的几种方法:
1.使用cin>>,这种方法只能输入不含空格的字符串,输入以空格、tab或回车结束。
2.使用cin.getline(),这种方法可以输入含有空格的字符串,输入以回车结束。
3.使用cin.get(),这种方法可以输入含有空格的字符串,输入以换行符结束。
下面是每种方法的示例代码:
1.使用cin>>:
```
string str;
cin >> str;
```
2.使用cin.getline():
```
char str[100];
cin.getline(str, 100);
```
3.使用cin.get():
```
char str[100];
cin.get(str, 100);
```
相关推荐
![](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)
![](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)