1

I'm trying to fill text document, but when I do - I get first line blank. My text document, I'm reading from, looks like this:

3
first fr random 5
second          9
third shazam    2

I've tried removing first value and so blank line went away. So it correlates, but I need that value.

// My code
ifstream in("U2.txt"); 
ofstream out("U2.txt");
int n;
in>>n;
char vardaiStart[n][21];

in.read(vardaiStart[0], 21);

out << vardaiStart[0]<< endl;

output looks like this:

*blank*
first fr random

but what I want is:

first fr random

So, in other projects I won't be using old C since now, but for this project I red that [endline] and ignored it like this: in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Lizard Derad
  • 272
  • 2
  • 17

1 Answers1

6

Your input file looks like:

3[endline]
first fr random 5[endline]
second          9[endline]
third shazam    2[endline]

Note the [endline] I added: they can be '\n', '\r\n' depending on the system that generated the file.

Your first instruction is:

in >> n;

a formatted input read: you are asking to read an integer from the file, so only characters that can form valid integers will be read.

This means that after that instruction the remaining portion of the file will be:

[endline]
first fr random 5[endline]
second          9[endline]
third shazam    2[endline]

The rest of your code reads raw bytes, so it will read the first [endline] as well (and print it).

As other suggested in the comments, you should not be using variable length arrays as they are not part of any C++ standard (but part of the C one). Try to use the C++ standard library instead.

marco6
  • 353
  • 2
  • 11