如何只使用一个for循环用C向后打印输入的字符串 [英] How to print an entered string backwards in C using only a for loop

查看:1130
本文介绍了如何只使用一个for循环用C向后打印输入的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向后打印一个字符串。但我的code似乎倒计时从最后一个字母在字母表阵列到阵列中的第一个字母,而不是倒计时阵列本身并吐出阵列中的每个字母。

I want to print a string backwards. But my code seems to count down the alphabet from the last letter in the array to the first letter in the array instead of counting down the array itself and spitting out each letter in the array.

我的code,

   #include <stdio.h>
   #include <string.h>

   int main(void) {

char word[50];
char end;
char x;

printf("Enter a word and I'll give it to you backwards: ");

scanf("%s", word);

end = strlen(word) - 1;

for (x = word[end]; x >= word[0]; x--) {
    printf("%c", x);
}

return 0;
}

有什么建议?谢谢你。

Any suggestions? Thank you.

推荐答案

您有什么数组元素值之间循环。你想数组索引之间循环。更新循环以下内容:

What you have loops between the array element values. You want to loop between the array indexes. Update your loop to the following:

for (x = end; x >= 0; --x) {
    printf("%c", word[x]);
}

请注意,这从最近指数变为零,输出的字符索引。另外一个微优化的使用pre-递减循环。

Note that this goes from the last index to zero and output the character at that index. Also a micro-optimization in the for loop using pre-decrement.

这篇关于如何只使用一个for循环用C向后打印输入的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆