简体   繁体   English

句子中单词倒序的问题

[英]Problem with reversing order of words in a sentence

I want to read inputtext.txt line by line and reverse the order of words in each line and print them out (input: hello world,output: world hello). 我想逐行阅读inputtext.txt并反转每行中单词的顺序并打印出来(输入:hello world,输出:world hello)。 With this code my output is all messed up and I get a runtime error #2 saying the stack around my array "string" is corrupted. 有了这段代码,我的输出全部混乱了,我收到了运行时错误2,指出数组“字符串”周围的堆栈已损坏。 I tried resetting the strings to null after each while loop iteration but I still get the same error. 我尝试在每次while循环迭代之后将字符串重置为null,但仍然遇到相同的错误。 Does anybody have any suggestions to get rid of the runtime error or help the code run more smoothly? 是否有人建议消除运行时错误或帮助代码更平稳地运行?

int main() {
    FILE *inp,*outp;        //file input and output
    int i,wordcount;                    //define counter variables
    int k = 0,j=0;
    char string[200];       //define string to scan sentence into
    char words[20][20];     //2D string for each word in the sentence
    inp = fopen("inputtext.txt", "r");
    outp = fopen("output.txt", "w");
    if (inp == NULL) {
        printf("File not found.\n");
    }
    else {
        while (!feof(inp)) {

            fgets(string, 1000, inp);
            printf("GOT SENTENCE\n");
            for (i = 0; string[i] != '\0'; i++) {


                if (string[i] == ' ') {
                    words[k][j] = '\0';
                    k++;
                    j = 0;
                }
                else
                {
                    words[k][j] = string[i];
                    j++;
                }

            }

            words[k][j] = '\0';
            wordcount = k;
            for (i = wordcount; i >= 0; i--) {
                printf("%s ", words[i]);
            }
            printf("\n\n");

        }
    }
    return 0;
}

the following proposed code: 以下建议的代码:

  1. cleanly compiles 干净地编译
  2. properly checks for errors 正确检查错误
  3. properly outputs error messages to stderr 正确将错误消息输出到stderr
  4. performs the desired functionality 执行所需的功能
  5. properly limits the max length of an input 适当限制输入的最大长度
  6. assumes no line in the input file is over 199 characters 假设输入文件中没有行超过199个字符
  7. minimizes the number of times the function: strlen() is called 最小化函数: strlen()的调用次数
  8. actually writes the reversed sentences to the output file 实际上将相反的句子写到输出文件

And now, the proposed code: 现在,建议的代码:

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


int main() 
{
    FILE *inp,*outp;        //file input and output
    int wordcount;                    //define counter variables
    int k = 0;
    int j = 0;
    char string[200];       //define string to scan sentence into
    char words[20][20];     //2D string for each word in the sentence

    inp = fopen("inputtext.txt", "r");
    if( !inp )
    {
        perror( "fopen to read: inputtext.txt failed" );
        exit( EXIT_FAILURE );
    }

    outp = fopen("output.txt", "w");
    if( !outp )
    {
        perror( "fopen to write: output.txt failed" );
        // cleanup
        fclose( inp );
        exit( EXIT_FAILURE );
    }


    size_t strLength = strlen( string );

    for (size_t i = 0; i < strLength; i++)
    {
        // remove any trailing newline
        string[ strspn( string, "\n" ) ] = '\0';

        printf("GOT SENTENCE\n");

        for (size_t i = 0; i < strlen(string); i++) 
        {
            if (string[i] == ' ') 
            {
                words[k][j] = '\0';
                k++;
                j = 0;
            }

            else
            {
                words[k][j] = string[i];
                j++;
            }
        }

        words[k][j] = '\0';
        wordcount = k;

        for ( int i = wordcount; i >= 0; i--) 
        {
            printf("%s ", words[i]);
            fprintf( outp, "%s ", words[i] );
        }
        printf("\n\n");
        fprintf( outp, "\n" );
    }

    return 0;
}

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

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