-3

我尝试了这段代码,但在for循环中它似乎什么也没做。

#include <stdio.h>
#include <stdlib.h>

void main()
{

    char word[100];
    char suf [100];
    int i,j,k = 0;
    char a [100];

    printf("Enter the word: \n");
    gets(word);
    printf("\n");



    for (i = strlen(word); i < 0; i--)
            {
                 a[i] = word[i];
                 printf("%s",a);

            }
}

示例输出:

>> 输入单词:程序

>> 米

>> 上午

>> 公羊

>> 克

>> 克

>> 罗格

4

2 回答 2

1

ALTERNATIVE : Use a pointer approach :

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

int main(int argc, const char * argv[])
{
    char word[100];

    printf("Enter the word: \n");
    gets(word);
    printf("\n");
    char *ptr;
    int len = (int)strlen(word) ;

    for (int i = len -1; i > 0; --i)
    {
        ptr = &word[i];
        printf("%s\n",ptr);

    }
    return 0;
}

Explanation :

Say the string you entered is program Now, the index ranges from 0 to 6 here, and not 7. In your code, you are starting with i = strlen(word) which is wrong. You should start with i = strlen(word) -1.

Also, you should decrement till the value of i is greater than 0 - not less as in your case i < 0.

SUGGESTIONS :

Do not use void main(……). Use int main(…). The former may not be supported on all compliers.

于 2014-08-05T15:10:33.230 回答
1

使用指针算法可能是最简单的方法。您甚至不需要临时缓冲区:

for (i = strlen(word) - 1; i > 0; --i) {
    printf("%s\n", word + i);
}
于 2014-08-05T15:02:34.203 回答