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

Talha Gillani picture Talha Gillani · Oct 10, 2015 · Viewed 8.7k times · Source

This program is for printing prime numbers till the input given and separating every prime number with a comma.

void main(){

    int N, counter=0, isPrime;

    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++;
            }
            k++;
        }
        if (isPrime==0){

            if (k==N){
                cout << j;
            }
            else{
                cout << j << ",";
            }
            counter++;
        }
    }
    cout << endl;
    system("pause");
}

It is only removing the last comma for prime number inputs, not for any other input. How can I fix this?

Input: 23
Output: 2,3,5,7,11,13,17,19,23
Input: 8
Output: 2,3,5,7,
Input: 9
Output: 2,3,5,7,

Answer

user5405790 picture user5405790 · Oct 10, 2015

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.