How can I remove the last comma from a loop in C++ in a simple way?

本小妞迷上赌 提交于 2019-12-01 20:02:01

There is no need to if then else so much:

std::string delim = "";
for( auto item : vec )
{
   std::cout << delim << item;
   delim = ",";
}

No checking is needed for all cases, like the vector is empty or not.

If you accept an extra space in the beginning, just replace the string to char, and then the performance will be improved even more.

Ben

Don't remove the last comma. Instead insert commas before each entry except the first.

Just decide from a pre condition:

bool first = true;
for(j=2;j<=N;j++){
   // ...
   if(k==N) {
   if(!first) {
       cout << ',';
   }
   else {
       first = false;
   }
   cout<<j;
}
Erman

To easily remove the last comma you can use the '\b' character.

for(auto item : vec)
    std::cout << item << ", " ;
std::cout << "\b\b " << std::endl;
EvgeniyZh

The easiest way is to output the first or last value manually:

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    int N, counter = 0;
    bool isPrime;

    cout << "Enter maximum range: ";
    cin >> N;
    if (N>=2) {
        cout << "2";
    }
    for (int j = 3; j <= N; ++j) {
        isPrime = true;
        for (int k = 2; k < sqrt(j)+1; ++k) {
            if (j % k == 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
            cout << ", " << j;
            counter++;
        }
    }
    cout << endl;
    system("pause");
}

With minimal changes to your existing code:

#include <iostream>
#include <string>

using namespace std;

void main()
{
    int N, counter = 0, isPrime;
    string separator = ""; // none at first
    int k, j;

    cout << "Enter maximum range: ";

    cin >> N;

    for(j = 2; j <= N; j++)
    {

        isPrime = 0;
        k = 2;

        while(k<j)
        {

            if(j%k == 0)
            {

                isPrime++;

                break; // exit while loop
            }
            k++;
        }
        if(isPrime == 0)
        {
            // if(k==N) not needed
            cout << separator << j;
            separator = ","; // comma after first
            counter++;
        }
    }
    cout << endl;
    system("pause");
}

Explanation
Basically, I added a separator string which is blank at the start, i.e. the empty string, but is set to a comma for each output after the first. As such the cout statement will not print a comma before the first number, but will do so for each subsequent number being printed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!