0

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 
6
  • 2
    char tmp[num+1]; is not valid C++. Use a vector or better yet std::string. Commented Oct 20, 2018 at 22:43
  • Does the code compile? When you say "the compiler is outputting" do you mean "the program is outputting"? What do you mean "with the newlines". Can you provide a full snippet of the output, that would help us understand the situation better. Commented Oct 20, 2018 at 22:50
  • The exercise requires use of c strings. Can you explain why that is not valid? Commented Oct 20, 2018 at 22:51
  • This char tmp[num+1] and this char data[num * num +1] are invalid syntaxes, the array size defined inside the square brackets must be a constant value. Commented Oct 20, 2018 at 22:54
  • what is the reason for disallowing variable length arrays. Commented Oct 20, 2018 at 22:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.