Darren Pan
Darren Pan

Reputation: 49

How can I remove the comma at the end of the output?

I am trying to write a program to split the numbers and the words. The code is completed, and it works. I'm just wondering how to remove the comma at the end of the output.

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;
vector<string> split(string targer, string delimiter);
int main()
{
   string s, delimiter;
   vector<string> tokens;
   cout << "Enter string to spilt:" << endl;
   getline (cin,s);
   cout << "Enter delimiter string:" << endl;
   getline (cin,delimiter);

   tokens = split(s, delimiter);
   cout << "The substrings are: ";
   for(int i = 0; i < tokens.size(); i++)
   {
    cout << "\"" << tokens[i] << "\"" << "," << " ";

   }
   cout<<endl;
   return 0;
}
vector<string> split(string target, string delimiter){
 stringstream ss(target);
 string item;
 vector<string> tokens;
 while (getline(ss, item, delimiter.at(0))) {
    tokens.push_back(item);
 }
 return tokens;
}

Upvotes: 2

Views: 1679

Answers (5)

songyuanyao
songyuanyao

Reputation: 172964

You can add an if condition for it:

for(int i = 0; i < tokens.size(); i++)
{
    if (i != 0) cout << "," << " ";
    cout << "\"" << tokens[i] << "\"";
}

or

string dlmtr = "";
for(int i = 0; i < tokens.size(); i++)
{
    cout << dlmtr << "\"" << tokens[i] << "\"";
    dlmtr = ", ";
}

Upvotes: 4

Khay Leng
Khay Leng

Reputation: 451

How about using backspace \b escape character?

Just outside of the for loop, add this ASCII character.

Upvotes: 0

Vaibhav Bajaj
Vaibhav Bajaj

Reputation: 1934

Try outputting the last cout statement outside the for loop like so:

PREVIOUS CODE:

for(int i = 0; i < tokens.size(); i++)
   {
    cout << "\"" << tokens[i] << "\"" << "," << " ";

   }
cout<<endl;

NEW CODE:

for(int i = 0; i < tokens.size() - 1; i++)
   {
    cout << "\"" << tokens[i] << "\"" << "," << " ";

   }
if (tokens.size() != 0)
    cout << "\"" << tokens[tokens.size() - 1] << "\"";
cout<<endl;

Upvotes: 1

BruceSun
BruceSun

Reputation: 166

size_t i = 0;

for(; i < tokens.size() - 1; i++) {
    cout << "\"" << tokens[i] << "\"" << "," << " ";
}

if (tokens.size() - 1 >= 0 ) {
    cout << "\"" << tokens[i] << "\"";
}

Upvotes: 0

user31264
user31264

Reputation: 6737

for(int i = 0; i < tokens.size(); i++)
{
     if (i > 0)
          cout << ", ";
     cout << '"' << tokens[i] << '"';
}

Upvotes: 1

Related Questions