Eidbanger Eidbanger - 1 year ago 104
C++ Question

How to not print the last comma of a list of integers?

This is when going through a list of integers in order seperated by commas and I only print one instance of an integer even where there are more than one seperated by commas. (CodeEval challenge https://www.codeeval.com/open_challenges/29/)

My problem is I am trying to do this in linear time without any external storage. And I can't have a comma at the end (e.g. 1,3,4,6,). The solutions I found online all use some list to store the integers and then they do a print.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
string str = "1,2,2,3,3,3,4,4";
char c;
int num = -1;
for (int i = 0; i < str.length(); ++i) {
if (str[i] == ',') continue;
else {
c = str[i];
if ((c - '0') != num) {
num = c - '0';
cout << num << ",";
cout << endl;
return 0;

Answer Source

One of the solution is to use boolean flag:

bool first = true;
for( ... ) {
    if( first ) first = false;
    else std::cout << ',';
    std::cout << data;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download