I'm trying to build a program that asks to user to input a positive integer and then the prime factors of this number are outputted. I'm giving the user three attempts to enter a valid input or the program ends. So any negative integers and non integers as well as other characters such as letters will give an error message. I'm nearly there but my output won't behave as I want. It treats decimal numbers as integers and negative numbers aren't returning the error.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <stdio.h>
using namespace std;
int main()
{
int num,i,flag,n;
//executes loop if the input fails (e.g., no characters were read)
while (cout << "Enter a number: " && !(cin >> num))
{
cin.clear(); //clear bad input flag
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //discard input
cout << "Invalid input, please re-enter: \n";
}
i=2;
n=num;
cout<< "\nThe Prime factors of "<< num << " are:"<< endl;
while(i<=num)
{
flag=0;
while(n%i==0)
{
n=n/i;
flag++;
}
if(flag>0)
{
cout <<i<< endl;
}
++i;
}
system("PAUSE");
return 0;
}