[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • Last Modified:

Operator overloading function - formatting?


Hello,

I have the following code:

            output << ", " << array[i];

This works fine but I'm left with an extra comma as it goes through a loop.

[, (0, 0), (0, 0)]

Any suggestions as to how I can remove the first comma + space white before the first open bracket ?

I've tried using output.ignore however this throws up an error ?

Thanks.
0
andyw27
Asked:
andyw27
  • 3
1 Solution
 
UrosVidojevicCommented:
try with this:

output << "[";
for (int i=0; i<array_size; i++) {
        output << array[i];
        if (i != array_size-1) output << ", ";
}
output << "]";
0
 
UrosVidojevicCommented:
Sample code:
============

_______________________________________________________________________________
#include <iostream>
using namespace std;

class Point {
      int x, y;
public:
      Point(int xx = 0, int yy = 0) { x = xx; y = yy; };
      friend istream& operator >> (istream& input, Point& p) {
            return input >> p.x >> p.y;
      }
      friend ostream& operator << (ostream& output, const Point& p) {
            return output << "(" << p.x << "," << p.y << ")";
      }
};

int main () {
      cout << "Number of points? ";
      int array_size;      
      cin >> array_size;
      Point array[array_size];
      for (int i = 0; i < array_size; i++) {
            cout << "Point #" << i+1 << " = ";
            cin >> array[i];
      }
      
      cout << endl;

      cout << "Array: ";
      cout << "[";
      for (int i=0; i<array_size; i++) {
                   cout << array[i];
                   if (i != array_size-1) cout << ", ";
      }
      cout << "]" << endl;
}
_______________________________________________________________________________



Sample input \ output:
======================
_______________________________________
Number of points? 4
Point #1 = 1 2
Point #2 = 3 4
Point #3 = 5 6
Point #4 = 7 8

Array: [(1,2), (3,4), (5,6), (7,8)]
_______________________________________

Regards, Uros.
0
 
UrosVidojevicCommented:
So, idea is to print comma+space after each element except the last. In that way you will get clear text formating.
0
 
andyw27Author Commented:

Thanks for the reply !!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now