0

I'm trying to write a piece of code that will only print a comma after an output if there is another output printed out after it. I use

  for(int j = 0; j < size; j++)
       {
          if(price[i][j] > 0)
          {
             cout << airports[j] << ", ";
          }
                  
       }

The problem is I don't know how to get rid of the last comma that is added with the last entry in the list. It outputs this:

Airports' destinations: 

BUR (3): LAX, SFO, SMO, 
LAX (1): BUR, 
SFO (2): BUR, SMO, 
SMO (2): BUR, SFO, 

How do I remove the comma at the end of every output?

Primey
  • 1

1 Answers1

0
for(int j = 0, comma = false; j < size; j++)
{
    if (price[i][j] > 0)
    {
        if (comma)
            cout << ", ";
        cout << airports[j];
        comma = true;
    }
}
273K
  • 29,503
  • 10
  • 41
  • 64
  • 2
    While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run. – jnovack Oct 03 '20 at 16:29
  • I'm confused about the boolean within the for loop. Is it possible to initializes another variable other than j? – Primey Oct 04 '20 at 07:32
  • [for loop](https://en.cppreference.com/w/cpp/language/for), look at *init-statement*. – 273K Oct 04 '20 at 16:09
  • The `init-statement` for a `for` loop can't declare multiple variables of *different* types, like this code is trying to do. You will have to move the `bool` outside of the loop instead: `bool comma = false; for(int j = 0; j < size; j++) { if (...) { ... comma = true; } }` – Remy Lebeau Apr 11 '22 at 22:19