从键盘上输入一个字符串(最多80个字符)并存入字符数组中,先输出其中所有下标为奇数的元素的值,换行;再输出其中所有下标为偶数的元素的值,最后换行。 输入格式: 从键盘上输入一个字符串(最多80个字符)并存入字符数组中。 输出格式: 先输出其中所有下标为奇数的字符,换行,再输出其中所有下标为偶数的字符,最后换行。 输入样例:,用c语言
时间: 2024-03-23 21:37:20 浏览: 27
好的,以下是使用C语言实现该题目的代码示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[81]; //定义字符数组
scanf("%s", str); //从键盘上输入字符串并存入字符数组中
//输出所有下标为奇数的元素的值
for (int i = 0; i < strlen(str); i++) {
if (i % 2 == 1) {
printf("%c", str[i]);
}
}
printf("\n"); //换行
//输出所有下标为偶数的元素的值
for (int i = 0; i < strlen(str); i++) {
if (i % 2 == 0) {
printf("%c", str[i]);
}
}
printf("\n"); //换行
return 0;
}
```
你可以将以上代码复制到C语言编译器中运行,输入一个字符串后即可得到结果。
相关问题
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++编译器中运行查看结果。如果有任何问题,请随时告诉我。