C语言 如何仅使用for循环在C中向后打印输入的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4331347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print an entered string backwards in C using only a for loop
提问by Corey
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.
我想向后打印一个字符串。但是我的代码似乎从数组中的最后一个字母到数组中的第一个字母倒数字母表,而不是倒数数组本身并吐出数组中的每个字母。
My 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.
有什么建议?谢谢你。
回答by Jason McCreary
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]);
}
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 循环中的微优化。
回答by Patrick Gombert
You're calling array values and not the specific index.
您正在调用数组值而不是特定索引。
for(x = end; x >= 0; x--) { printf("%c", word[x]); }
回答by Anon.
You want to print word[x](the xth character in the array) instead of x(the xth character in the character set).
您想打印word[x](数组中的第 x 个字符)而不是x(字符集中的第 x 个字符)。
You also want to be counting down indexes, not characters.
您还想倒数索引,而不是字符。
for(x=end, x >= 0; x--)
printf("%c", word[x]);
回答by ysap
In your loop, xis the index into the character array comprising word. So xshould change from endto 0, and referencing the array should be as word[x].
在您的循环中,x是包含word. 所以x应该从endto改变0,并且引用数组应该是 as word[x]。
回答by venom
//Change end to int type and modify your for loop as shown.
#include <stdio.h>
#include <string.h>
int main(void)
{
char word[50];
int end;
char x;
printf("Enter a word and I'll give it to you backwards: ");
scanf("%s", word);
end = strlen(word) - 1;
for (x = end; x >= 0; x--)
printf("%c",word[x] );
return 0;
}
回答by Marin Alexandru
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(int argc, char** argv) {
int i;
char letters[3]="";
printf("Enter three letters!");
scanf("%s",letters);
for(i=3;i>=0;i--){
printf("%c", letters[i]);
}
return (EXIT_SUCCESS);
}

