0

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:

Lorem ipsum 
dolor sit 
amet

Expected output (File Out.txt):

Lorem ipsumsmt 
dolor sitsmt 
ametsmt

But what I get in Out.txt:

Lorem ipsum 
smtdolor sit 
smtamet
smt

So how to get expected result?

P.S. I think that the problem occurs when I use function fgets().

Natasha Dutta
  • 3,242
  • 21
  • 23
k1ber
  • 180
  • 1
  • 13

2 Answers2

5

This is not a bug or problem, rather, an expected behavior. Please read on.

fgets() reads and stores the trailing newline (\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. May overflow.

  2. make sure your buff[i] is big enough to hold the concatenated string. Otherwise, it will invoke undefined behaviour.

Natasha Dutta
  • 3,242
  • 21
  • 23
1

Below code will work for you. You need to add Null Character before doing any String operations. 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;
}
Amol Saindane
  • 1,568
  • 10
  • 19