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

后端 未结 6 1329
梦毁少年i
梦毁少年i 2020-12-06 13:31

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;
         


        
6条回答
  •  北海茫月
    2020-12-06 14:07

    With minimal changes to your existing code:

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

    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.

提交回复
热议问题