Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ How can i remove the last comma?

    #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,

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading