0

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!

shadowspawn
  • 3,039
  • 22
  • 26
pancakes324
  • 11
  • 1
  • 3
  • 1
    it's not very clear to me. can you please add some more detail? – dj1986 Apr 11 '20 at 05:50
  • 1
    Given the instructions, that does not appear to be the intended approach. Your approach outputs data **with** '"\n"', does it not? – JaMiT Apr 11 '20 at 05:51
  • I'm given an array of integers and the file I am reading will give me commands to traverse a tree in either preorder, postorder and inorder with the integers. I am suppose to output the integers in by whatever command I am given. When outputting the data should be in one line without “\n”. When outputting for a new command, a new line should be started. – pancakes324 Apr 11 '20 at 06:34

1 Answers1

2

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
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302