使用strcat

时间:2015-06-05 13:34:16

标签: c arrays string file-io fgets

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

#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

预期输出(File Out.txt):

Lorem ipsumsmt 
dolor sitsmt 
ametsmt

但是我在Out.txt中得到了什么:

Lorem ipsum 
smtdolor sit 
smtamet
smt

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

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

2 个答案:

答案 0 :(得分:5)

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

fgets()读取并存储尾随换行符(\n)。你需要在存储输入之前删除(剥离)。

那就是说,请注意:

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

  2. 确保您的buff[i]足以容纳连接的字符串。否则,它将调用undefined behaviour

答案 1 :(得分:1)

以下代码适合您。在执行任何String操作之前,您需要添加Null Character。我在任何地方修改了代码。

#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;
}
相关问题