#include <iostream>
using namespace std;
int main() {
string x;
cin >> x;
char ch;
/* how can i remove the last comma? */
int l = x.length();
for (int i = 0; i < l; i ) {
ch = x.at(i);
cout << ch << ",";}
return 0;
}
I expect: input: 1234 output: 1,2,3,4 but now: input: 1234 output: 1,2,3,4,
CodePudding user response:
Just print the first char and then print all the other elements preceeded by a comma. You need to deal with the special case of the empty string of course:
if (!x.empty())
{
std::cout << x[0];
for (auto pos = x.begin() 1; pos != x.end(); pos)
{
std::cout << ',' << *pos;
}
}
std::cout << '\n';
CodePudding user response:
Do this(Basically you print the comma separately between that you check if it is the last iteration and works for any numbers):
#include <iostream>
using namespace std;
int main() {
string x;
cin >> x;
char ch;
/* how can i remove the last comma? */
int l = x.length();
for (int i = 0; i < l; i ) {
ch = x.at(i);
cout << ch ;
if (i==l-1) {break;}
cout << ",";}
return 0;
}