简体   繁体   English

使用strcat的错误字符串连接

[英]Wrong string concatenation using strcat

I'm writing a program that reads strings from file, saves them to 'string buffer' and then concatenates those string and writes them to another file. 我正在编写一个程序,该程序从文件中读取字符串,将其保存到“字符串缓冲区”,然后将这些字符串连接起来并将它们写入另一个文件。

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

Contents of file Read.txt: 文件Read.txt的内容:

Lorem ipsum 
dolor sit 
amet

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

Lorem ipsumsmt 
dolor sitsmt 
ametsmt

But what I get in Out.txt: 但是我在Out.txt中得到的是:

Lorem ipsum 
smtdolor sit 
smtamet
smt

So how to get expected result? 那么如何获得预期的结果呢?

PS I think that the problem occurs when I use function fgets() . PS我认为当我使用函数fgets()时会出现问题。

This is not a bug or problem, rather, an expected behavior. 这不是错误或问题,而是预期的行为。 Please read on. 请继续阅读。

fgets() reads and stores the trailing newline ( \\n ). fgets()读取并存储结尾的换行符( \\n )。 you need to remove (strip) that before storing the input. 您需要先删除(剥离)存储输入的内容。

That said, please note: 也就是说,请注意:

  1. Please don't allow boundless increment of i when you have defined a fixed size buffer. 当您定义了固定大小的缓冲区时,请不要无限增大i May overflow. 可能溢出。

  2. make sure your buff[i] is big enough to hold the concatenated string. 确保您的buff[i]足够大,可以容纳串联的字符串。 Otherwise, it will invoke undefined behaviour . 否则,它将调用未定义的行为

Below code will work for you. 下面的代码将为您服务。 You need to add Null Character before doing any String operations. 在执行任何String操作之前,您需要添加Null字符 I commented the code wherever I modified. 无论我在哪里修改,我都会注释代码。

#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