Printing an array line by line but not ending with '\n' on the last line?

66 Views Asked by At

I am currently working on a program and one of the instructions states:

"For the output file, when outputting for one command, the data should be in one line without “\n”. When outputting for a new command, a new line should be started."

Would the best option in this case be to have a counter for the amount of commands and then checking if it's greater than 1, if it is then cout << data << endl; until you've reached the last one and then cout << data;? I feel like that's a really inefficient way of doing this and there is a better solution than this? Thank you!

1

There are 1 best solutions below

0
On

idioms-for-for-each-between-each-consecutive-pair-of-elements does mostly literally "When outputting for a new command, a new line should be started."

const auto* separator = "\n";
const auto* sep = "";
for(const auto& command : commands) {
    std::cout << sep << command;
    sep = separator; // No longer first command
}