c - 在 C 中反向打印字符串

标签 c string reverse

我正在编写一个程序,它将一些文件作为参数并反转打印所有行。问题是我得到了意想不到的结果:

如果我将它应用于包含以下行的文件

one
two
three
four 

我得到了预期的结果,但是如果文件包含

september
november
december

返回

rebmetpes
rebmevons
rebmeceds

我不明白为什么最后要加一个“s”

这是我的代码

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

void reverse(char *word);

int main(int argc, char *argv[], char*envp[]) {
    /* No arguments */
    if (argc == 1) {
        return (0);
    }

    FILE *fp;

    int i;
    for (i = 1; i < argc; i++) {
        fp = fopen(argv[i],"r"); // read mode

        if( fp == NULL )
        {
            fprintf(stderr, "Error, no file");
        }

        else
        {
            char line [2048];
/*read line and reverse it. the function reverse it prints it*/
            while ( fgets(line, sizeof line, fp) != NULL )
                reverse(line);  
        }
        fclose(fp);
    }

    return (0);
}

void reverse(char *word)
{
    char *aux;
    aux = word;
    /* Store the length of the word passed as parameter */
    int longitud;
    longitud = (int) strlen(aux);

    /* Allocate memory enough ??? */
    char *res = malloc( longitud * sizeof(char) );

    int i;

    /in this loop i copy the string reversed into a new one
    for (i = 0; i < longitud-1; i++)
    {
        res[i] = word[longitud - 2 - i];
    }

    fprintf(stdout, "%s\n", res);
    free(res);
}

(注意:为清楚起见,删除了一些代码,但应该可以编译)

最佳答案

您忘记以 \0 字符结束您的字符串。在反转字符串时,\0 成为反转字符串的第一个字符。首先为比你分配的多一个字符分配内存

char *res = malloc( longitud * sizeof(char) + 1);  

然后试试这个

for (i = 0; i < longitud-1; i++)
{
    res[i] = word[longitud - 2 - i];
}
res[i] = '\0'; // Terminating string with '\0'

关于c - 在 C 中反向打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20143223/

相关文章:

c - 程序如何继承环境变量?

c - 从标准输入读入文件*

c - scanf 多个变量或一个变量

java - 使用 Android Studio 格式化 JAVA 中的字符串

php - 使用 php 在 varchar 字段中插入带斜杠的查询

c++ - 反转堆栈时出错,你能指出来吗?

c - 错误; 'else' 之前的预期表达式

java - String.codePointAt 到底是做什么的?

c - 在 C 中反转数组逻辑无法正常工作

c++ - boost::dynamic_bitset 的逆序