编写程序,输入一个字符串,按照相反次序输出其中所有字符
时间: 2024-04-09 07:27:59 浏览: 38
下面是一个C语言程序示例,用于输入一个字符串,然后按照相反的顺序输出其中的所有字符:
```c
#include <stdio.h>
#include <string.h>
void reversePrint(char *str) {
int length = strlen(str);
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
}
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
// 去除换行符
if (str[strlen(str) - 1] == '\n') {
str[strlen(str) - 1] = '\0';
}
printf("按相反次序输出结果:");
reversePrint(str);
return 0;
}
```
程序中的`reversePrint`函数接受一个字符串作为参数,使用循环从字符串末尾开始逐个输出字符。在`main`函数中,首先使用`fgets`函数从标准输入获取字符串,并去除换行符。然后调用`reversePrint`函数输出结果。
运行程序后,输入一个字符串,程序将按照相反的顺序输出其中的所有字符。
相关问题
用c语言编写程序输入一个字符串,按相反次序输出其中的所有字符
Sure! Here's a C program that takes a string input from the user and outputs all the characters in reverse order:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int length = strlen(str);
// Reversing the string
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
}
int main() {
char input[100];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
printf("Reversed string: ");
reverseString(input);
return 0;
}
```
In this program, we define a function `reverseString` that takes a character array (`str`) as input and prints each character in reverse order. In the `main` function, we ask the user to enter a string using `fgets` and then call the `reverseString` function passing the user's input.
Please note that this program assumes the input string will be less than or equal to 100 characters in length. If you need to handle longer strings, you can increase the size of the `input` array accordingly.
编写C语言程序,定义字符指针变量p,实现输入一个字符串,按相反次序输出其中的所有字符。
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
char *p;
printf("请输入一个字符串:");
gets(str); // 推荐使用fgets(str, 100, stdin)替代
p = str + strlen(str) - 1; // 指向字符串最后一个字符
printf("相反次序输出:");
while (p >= str) {
printf("%c", *p);
p--;
}
printf("\n");
return 0;
}
```
这里使用了指针来实现字符串的反转输出。首先,定义一个字符数组 `str`,用于存储输入的字符串。然后定义一个字符指针 `p`,指向字符串 `str` 的最后一个字符。接着,通过 `while` 循环遍历字符串,从最后一个字符开始输出,直到遍历到字符串的第一个字符。在循环内部,使用 `printf` 函数输出指针 `p` 指向的字符,然后将指针 `p` 向前移动一个位置,以便输出下一个字符。最后,输出一个换行符,结束程序的执行。