简体   繁体   English

为什么这个逆句算法不起作用?

[英]Why is this reversing sentence algorithm not working?

There are some comments in the code for human-readable code:对于人类可读的代码,代码中有一些注释:

#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);
}

The program theoretically looks fine, but when it is executed, it sometimes print garbage values, only some words, or sentence which has only reversed half with garbage value instead of spaces.该程序理论上看起来不错,但是当它执行时,它有时会打印垃圾值,只打印一些单词,或者只用垃圾值而不是空格反转一半的句子。

The program above is to save each word to the temp, and reverse temp (temp is reversed when storing the word) back to the output.上面的程序就是把每个word保存到temp,reverse temp(存储word的时候temp被反转)回输出。 However, it fails.但是,它失败了。

Thank you for your help.感谢您的帮助。

There are at least three problems.至少存在三个问题。

The first problem is that you never terminate the string o To do that change:第一个问题是您永远不会终止字符串o要进行更改:

   printf("%s", o);

into进入

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

The second problem is that you increment it_r incorrectly.第二个问题是你错误地增加了it_r Change改变

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

into进入

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

The third problem is that you don't handle the first word of the input (because there is no space in front).第三个问题是你没有处理输入的第一个单词(因为前面没有空格)。 I'll leave that problem to you as an exercise.我会把这个问题留给你作为练习。

BTW: Don't use gets for reading input.顺便说一句:不要使用gets来读取输入。 Use fgets instead.请改用fgets

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

#define SIZE 100   //The size of input array is prefered to be equal to ouput array.
int main(){
   char input[SIZE];
   char output[SIZE];
   int i = 0, j = 0;
   //i is the iterator to the input sentence,
   //j is the iterator to the output sentence
   printf("Enter a sentence:");
   gets(input);
   int len = strlen(input) - 1; //Total length.
   j = len;
   while(input[i]!= NULL){
            output[j] = input[i];  
            i++;
            j--;            
   }
    output[len+1]= NULL;
    printf("%s", output);
    printf("Finished");
 }

Try the modified code given below, the changed sections has been commented(all other comments were removed for readability)尝试下面给出的修改后的代码,更改的部分已被注释(为了可读性,所有其他注释都被删除)

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

#define SIZE 100
#define ACCUM_CHAR_SIZE 25  
int main(){
   char i[SIZE];
   char acc[ACCUM_CHAR_SIZE];
   char o[SIZE];
   int it_l = 0, it_a = 0, it_r = 0;

   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];  
            it_a++;
        }
        else{
            it_a -= 1;
            while(it_a >= 0){
                o[it_r] = acc[it_a];
                it_r++;
                it_a--;
            }
            /*it_r += 1; There is no need to increment it_r here as
              it is already incremented in the above loop*/
            o[it_r] = 32;
            it_r += 1;  /* The above increment statement was moved here(only 
            incremented when a new value is loaded in to output array) */
            it_a = 0;  
            strcpy(acc, ""); 
        }
        it_l++;
   }
  /* The below section reverses and stores the first word of the
   input which was not getting operated in the above loop */
   it_a -= 1;
    while(it_a >= 0){
        o[it_r] = acc[it_a];
        it_r++;
        it_a--;
    }
   o[it_r] = '\0'; // Terminating output array
   printf("%s", o);
}

The above code will work as expected but has some small issues(given below)上面的代码将按预期工作,但有一些小问题(如下所示)

  1. Using gets():- gets is not recommended for inputting strings.不推荐使用gets():-gets 来输入字符串。 See this link for more info.有关更多信息,请参阅此链接

  2. The Size of temporary array acc :- If a word greater than 25 characters is inputted the program may output garbage value.临时数组acc的大小:- 如果输入大于25 个字符的单词,程序可能会输出垃圾值。

Version without temporary storage.没有临时存储的版本。

  • read the input string from start (0)从开始(0)读取输入字符串
  • copy any word from input into output, starting from the end of output - words are not reversed将输入中的任何单词复制到输出中,从输出的末尾开始 - 单词不会反转
  • copy any space in output, from position in output, starting from the end复制输出中的任何空间,从输出中的位置,从末尾开始

Code代码

#define SIZE 100   //size of the input array and output array

int main(){
    char i[SIZE];
    char o[SIZE];

    printf("Enter a sentence: ");
    fgets(i, SIZE, stdin);     // fgets instead of gets

    int j,len = strlen(i) - 1; // assuming you eat the EOL character
    o[len] = '\0';             // start by marking end of output string

    for(j=0 ; j<len ; j++) {   // navigating the input string
        if (i[j] == ' ') {
            o[len-j-1] = i[j]; // if space, copy (from end) in output
        }
        else {
            int k=j;
            do {
                k++;           // count(+1) the word, non-space, characters
            } while (k<len && i[k] != ' ');
            strncpy(&o[len-k], &i[j], k-j); // copy the word
            j = k-1;
        }
    }

   printf("%s\n", o);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM