Home > Back-end >  How to remove the end space in this for loop in c /cpp?
How to remove the end space in this for loop in c /cpp?

Time:07-06

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    cin >> n; cin.ignore();

    for(int i = 1; i < 11; i  ){
        cout << i * n << " ";
    }

}

Output must be like this ->

Found:

"1 2 3 4 5 6 7 8 9 10 " //wrong (at the end there is a space)

Expected:

"1 2 3 4 5 6 7 8 9 10" //correct (at the end there is no space)

CodePudding user response:

A simple approach is the following

for( int i = 0; i < 10; i  ){
    if ( i ) cout << ' ';
    cout << ( i   1 ) * n;
}

CodePudding user response:

The standard approach is to use a boolean variable, which is one time either true or false, then print a space or not, depending on the boolean, and set the boolen to a new value.

Often the output of the space in the loop is done first and then then value.

Example:

bool printSpace = false;
for(int i = 1; i < 11;   i) {
    if (printSpace) std::cout << ' ';
    printSpace = true;
    std::cout << i * n;
}

You could also use std::exchange for flipping the bool. Please read here.

Then you could do something like the below:

#include <iostream>
#include <vector>
#include <utility>

int main() {
    
    std::vector data{1,2,3,4};
    
    bool showComma{};
    for (const int i: data) 
        std::cout << (std::exchange(showComma, true) ? "," : "") << i;
}

And the super high sophisticated stuff will be done with the std::ostream_joiner.

Reade here for an example. But, unfortunately this is not available for many installations.

  • Related