Adrian5404
Adrian5404

Reputation: 3

Reading data from file into string

I am trying to read a file and put data into string. However the compiler is outputting this.

012  
345  
678  
����012345678  

with the new lines. Can you explain what is happening?

#include <iostream>

using namespace std;
#include <fstream>
#include <cstring>
int main() {
  ofstream output("transform.out");
  ifstream input("transform.in"); 
  int num = 0;
  input >> num; 
  char tmp[num+1];
  char data[num * num +1];
  while(input >> tmp){
    cout << tmp << '\n';
    strcat(data, tmp);
  }
  cout << data; 
}

transform.in has this data

3
012
345
678

Upvotes: 0

Views: 110

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

Note that standard C++ does not support variable length arrays like char data[num * num +1] (num is not a constexpr). Your code compiles because you probably use a compiler with an extension supporting VLAs. For portable code, however, you'd need to use some dynamic data structures, e.g. a vector.

Anyway, you do not initialize data, such that your very first strcat might append a (valid) content of tmp to data that starts with garbage. Your output ���� is not a result of a newline but just that garbage to which the very first strcat appends your file contents.

char data[num * num +1] = { 0 }; should solve this problem.

Upvotes: 4

Related Questions