0

I am trying to get the factors of positive integer. What I want is 8 = 2*2*2. However, what I get is *2*2*2. How can I get ride of the first *? Is there a standard way to better describe this situation?

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
    int num, i = 2;
    const char separator  = '*';
    cout << "Input a positive integer: ";
    cin >> num;
    while(num !=1){
        while((num % i) != 0){
            i++;
        }
        cout << setw(2) << setfill(separator) << i;
        num = num/i;
    }
}

Input a positive integer: 8

*2*2*2

Jill Clover
  • 2,168
  • 7
  • 31
  • 51
  • The easiest way to remove something is to not add it in the first place. – 1201ProgramAlarm Jan 12 '16 at 03:31
  • Does this answer your question? [How can I remove the last comma from a loop in C++ in a simple way?](https://stackoverflow.com/questions/33054983/how-can-i-remove-the-last-comma-from-a-loop-in-c-in-a-simple-way) – ShadowRanger Mar 11 '20 at 17:08

2 Answers2

1

Use a separator that is updated. Start with "" and set to "*" thereafter.

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
    int num, i = 2;
    const char *separator  = "";
    cout << "Input a positive integer: ";
    cin >> num;
    do {
        while((num % i) != 0){
            i++;
        }
        cout << separator << i;
        separator  = "*";
        num = num/i;
    } while (num > 1);
}

Also changed to do loop to cope with num == 1 and num == 0 which print nothing in OP's original code. Code could use unsigned as a further extension/ protection.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

One way to accomplish that is by outputting setfill(separator) only when num is not equals to 1.

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
    int num, i = 2;
    const char separator  = '*';
    cout << "Input a positive integer: ";
    cin >> num;
    while(num !=1){
        while((num % i) != 0){
            i++;
        }
        cout << setw(2) << i;
        num = num/i;
        if (num != 1)
            cout << setfill(separator);
    }
}
Arturo
  • 51
  • 4