c加加从键盘输入一个字符,如果是字母,就输出其对应的ASCII码;如果是数字字符,就转换成对应整数并输出
时间: 2023-05-11 07:03:51 浏览: 141
可以使用以下代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
char c;
cin >> c;
if (c >= 'a' && c <= 'z') {
cout << (int)c << endl;
} else if (c >= 'A' && c <= 'Z') {
cout << (int)c << endl;
} else if (c >= '0' && c <= '9') {
cout << (int)(c - '0') << endl;
}
return 0;
}
```
如果输入的是字母,就将其转换成对应的 ASCII 码并输出;如果输入的是数字字符,就将其转换成对应的整数并输出。
相关问题
C加加实现输入一串字符大写转换成小写小写转换成大写其他字符原样输出
```c++
#include <iostream>
using namespace std;
int main() {
char c;
while(cin >> c) {
if(c >= 'a' && c <= 'z') {
c = c - 'a' + 'A';
} else if(c >= 'A' && c <= 'Z') {
c = c - 'A' + 'a';
}
cout << c;
}
return 0;
}
```
说明:
1. 通过 `cin` 读取字符,如果读取到文件结尾或遇到输入错误将退出循环。
2. 判断字符的大小写,如果是小写字母将其转换为大写字母,如果是大写字母将其转换为小写字母。
3. 输出转换后的字符。
C加加循环结构输入一行字符不超过200个分别统计其中英文字母空格数字其他字符的个数
以下是C++代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
char str[201]; // 存储输入的字符串
int letter = 0, space = 0, digit = 0, other = 0; // 统计各类字符的个数
cout << "请输入一行字符(不超过200个):" << endl;
cin.getline(str, 201); // 读取一行字符串
// 循环遍历字符串中的每个字符
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 判断是否为字母
letter++;
} else if (isspace(str[i])) { // 判断是否为空格
space++;
} else if (isdigit(str[i])) { // 判断是否为数字
digit++;
} else { // 其他字符
other++;
}
}
// 输出结果
cout << "英文字母个数:" << letter << endl;
cout << "空格个数:" << space << endl;
cout << "数字个数:" << digit << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
说明:
- 使用 `cin.getline()` 函数读取一行字符串,存储到字符数组 `str` 中;
- 循环遍历字符数组 `str` 中的每个字符,使用 `isalpha()`、`isspace()`、`isdigit()` 函数判断字符类型;
- 使用计数器变量 `letter`、`space`、`digit`、`other` 统计各类字符的个数;
- 输出结果。