【发布时间】:2017-02-23 20:20:01
【问题描述】:
这里是初级程序员。我正在尝试从用户那里获取输入,将其反转并显示结果。出于某种原因,它打印的是空白而不是反转的字符串。我知道array[i] 有正确的信息,因为如果我在for (int i=0; i<count; i++) 线上使用这个循环,它会打印正确的字符。它只是没有反向打印。我在这里没有得到什么?
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
printf("Please enter a word: ");
char *word = get_string();
int count = strlen(word);
char array[count];
for (int i=0; i< count; i++)
{
array[i] = word[i];
}
for (int i=count-1; i==0; i--)
{
printf("%c ", array[i]);
}
printf("\n");
}
【问题讨论】:
-
你的条件不对。应该是:
for (int i=count-1; i>=0; i--) -
在其他地方逐字复制输入有什么意义?为什么不直接从原处打印呢?
-
如果你想反转字符串,你的第一个 for 循环必须改变。一个数组向上计数,另一个数组向下计数
-
@P.P.谢谢,我不知道为什么我没有想到。
-
@DavidSchwartz 一开始我在一个数组中完成了所有操作,将其分解以更好地调试它。