繁体   English   中英

使用strcat的错误字符串连接

[英]Wrong string concatenation using strcat

我正在编写一个程序,该程序从文件中读取字符串,将其保存到“字符串缓冲区”,然后将这些字符串连接起来并将它们写入另一个文件。

#define _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <stdio.h>

int main() {
    FILE *f = fopen("Read.txt", "r");
    char line[20];
    char buff[15][20];
    int i = 0;
    while (fgets(line, 18, f)) {
        strcpy(buff[i], line);
        i++;
    }
    FILE *h = fopen("Out.txt", "w+");
    for (int j = 0; j < i; ++j) {
        char ct[4] = "smt";
        strcat(buff[j], ct);
        fputs(buff[j], h);
    }
    return 0;
}

文件Read.txt的内容:

Lorem ipsum 
dolor sit 
amet

预期输出(文件Out.txt):

Lorem ipsumsmt 
dolor sitsmt 
ametsmt

但是我在Out.txt中得到的是:

Lorem ipsum 
smtdolor sit 
smtamet
smt

那么如何获得预期的结果呢?

PS我认为当我使用函数fgets()时会出现问题。

这不是错误或问题,而是预期的行为。 请继续阅读。

fgets()读取并存储结尾的换行符( \\n )。 您需要先删除(剥离)存储输入的内容。

也就是说,请注意:

  1. 当您定义了固定大小的缓冲区时,请不要无限增大i 可能溢出。

  2. 确保您的buff[i]足够大,可以容纳串联的字符串。 否则,它将调用未定义的行为

下面的代码将为您服务。 在执行任何String操作之前,您需要添加Null字符 无论我在哪里修改,我都会注释代码。

#define _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <stdio.h>

int main() {
    FILE *f = fopen("Amol.txt", "r");
    char line[20];
    char buff[15][20];
    int i = 0;
    while (fgets(line, 18, f)) {
        line[strlen(line) -1] = '\0';  // Here I added NULL character 
        strcpy(buff[i], line);
        i++;
    }
    FILE *h = fopen("Out.txt", "w+");
    for (int j = 0; j < i; ++j) {       
        char ct[5] = "smt\n";       // As \n will be at the end,so changed this array
        strcat(buff[j], ct);        
        fputs(buff[j], h);
    }
    return 0;
}

暂无
暂无

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

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