从键盘上输入一个字符串(最多80个字符)并存入字符数组中,先输出其中所有下标为奇数的元素的值,换行;再输出其中所有下标为偶数的元素的值,最后换行。 输入格式: 从键盘上输入一个字符串(最多80个字符)并存入字符数组中。 输出格式: 先输出其中所有下标为奇数的字符,换行,再输出其中所有下标为偶数的字符,最后换行。c语言
时间: 2024-03-23 10:38:41 浏览: 109
这是一段 C 语言的代码,实现的功能是输入一个字符串,然后按照奇偶位置分别输出其中的字符。具体来说,先输出所有奇数位置上的字符,再输出所有偶数位置上的字符。
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[81];
fgets(str, 81, stdin);
int len = strlen(str);
for (int i = 0; i < len; i += 2) {
putchar(str[i]);
}
putchar('\n');
for (int i = 1; i < len; i += 2) {
putchar(str[i]);
}
putchar('\n');
return 0;
}
```
其中,fgets 函数用于安全地读取用户输入,防止输入超出数组范围造成的错误。
相关问题
c语言从键盘上输入一个字符串(最多80个字符)并存入字符数组中,先输出其中所有下标为奇数的元素的值,换行;再输出其中所有下标为偶数的元素的值,最后换行。
好的,下面是 C 语言的代码实现:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 80
int main() {
char str[MAX_LEN];
printf("请输入一个字符串(最多80个字符):");
fgets(str, MAX_LEN, stdin);
int len = strlen(str);
printf("下标为奇数的元素值:\n");
for (int i = 0; i < len; i += 2) {
printf("%c ", str[i]);
}
printf("\n下标为偶数的元素值:\n");
for (int i = 1; i < len; i += 2) {
printf("%c ", str[i]);
}
printf("\n");
return 0;
}
```
程序先提示用户输入一个字符串,使用 `fgets()` 函数从标准输入中读入字符串,并将其存入字符数组 `str` 中。然后,程序计算字符串的长度,并分别输出下标为奇数和偶数的元素值,每行一个元素值,最后单独输出一个换行符。
从键盘上输入一个字符串(最多80个字符)并存入字符数组中,先输出其中所有下标为奇数的元素的值,换行;再输出其中所有下标为偶数的元素的值,最后换行。
好的,我可以回答你的问题。以下是实现这个任务的C++代码:
```c++
#include <iostream>
using namespace std;
int main() {
char str[81]; // 定义一个字符数组,长度为81,可存放最多80个字符
cin.getline(str, 81); // 从键盘输入字符串,存放在字符数组中(可输入空格)
// 输出所有下标为奇数的元素
for (int i = 0; str[i] != '\0'; i++) {
if (i % 2 == 1) {
cout << str[i];
}
}
cout << endl; // 换行
// 输出所有下标为偶数的元素
for (int i = 0; str[i] != '\0'; i++) {
if (i % 2 == 0){
cout << str[i];
}
}
cout << endl; // 换行
return 0;
}
```
你可以复制以上代码,在C++编译器中运行查看结果。如果有任何问题,请随时告诉我。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![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_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)