首页 > 解决方案 > 为什么这个倒置句子算法不起作用?

问题描述

代码中有一些人类可读代码的注释:

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

#define SIZE 100   //size of the input array and output array
#define ACCUM_CHAR_SIZE 25  //size of the temp array
int main(){
   char i[SIZE];
   char acc[ACCUM_CHAR_SIZE];
   char o[SIZE];
   int it_l = 0, it_a = 0, it_r = 0;
   //it_l is the iterator to the input sentence,
   //it_a is the iterator to the temp array
   //it_r is the iterator to the output sentence
   printf("Enter a sentence:");
   gets(i);
   int len = strlen(i) - 1;
   while(it_l <= len){
        if(i[len - it_l] != ' '){
            acc[it_a] = i[len - it_l];  //add letters to acc until space
            it_a++;
        }
        else{
            it_a -= 1;
//acc is reversed, I reversed it again to the output sentence
            while(it_a >= 0){
                o[it_r] = acc[it_a];
                it_r++;
                it_a--;
            }
            it_r += 1;
            o[it_r] = 32;   //put a space
            it_a = 0;  //reset the temp array
            strcpy(acc, ""); //clear the acc
        }
        it_l++;
   }
   printf("%s", o);
}

该程序理论上看起来不错,但是在执行时,有时会打印垃圾值,仅打印一些单词或仅用垃圾值而不是空格反转一半的句子。

上面的程序是将每个单词保存到temp,然后将temp(存储单词时temp反转)返回到输出。但是,它失败了。

感谢您的帮助。

标签: c

解决方案


至少存在三个问题。

第一个问题是您永远不会终止字符串o要进行更改:

   printf("%s", o);

进入

   o[it_r] = '\0';
   printf("%s", o);

第二个问题是您it_r错误地递增。改变

        it_r += 1;
        o[it_r] = 32;   //put a space

进入

        o[it_r] = ' ';  // Use ' ' instead of 32
        it_r += 1;

第三个问题是你不处理输入的第一个单词(因为前面没有空格)。我会把这个问题留给你作为练习。

顺便说一句:不要gets用于读取输入。改为使用fgets


推荐阅读