This code prompts the user to enter a number and returns the number with a statement if it is prime or not. It also includes "," to separate every 3 digits. I modified the code so that the user could have a choice of three separators(comma, space, period).

I thought there might be a way to use a control structure to use three different #define commands...something like...

Code:

if(choice == 1)
#define GROUP_SEP ','
else if (choice == 2)
#define GROUP_SEP ' '
else if (choice == 3)
#define GROUP_SEP '.'

The code below works, but I couldn't use the above approach. It would crash my program. Any ideas why?

Code:

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <sstream>
using namespace std;
string output_formatted_string(long long num);
string determine_separator(int choice);
int main() {
long long int n; // Number to test for prime-ness, long long data type
int i ; // Loop counter
int is_prime = true; // Bool ean fl ag. . .
// Assume true for now.
// Get a number from the keyboard.
cout << "Enter a number and press ENTER: " << endl;
cin >> n;
// Test for pri me by checki ng for di vi si bi l i ty
// by al l whol e numbers from 2 to sqrt(n) .
i = 2;
while (i <= sqrt(n) ) { // Whi l e i i s <= sqrt(n) ,
if (n % i == 0) // If i di vi des n,
is_prime = false; // n i s not pri me.
i++; // Add 1 to i .
}
// Pri nt resul ts
string s = output_formatted_string(n);
if (is_prime)
cout << s <<" is prime. " << endl ;
else
cout << s <<" is not prime." << endl;
system("PAUSE");
return 0;
}
//#define GROUP_SEP ','
#define GROUP_SIZE 3
string output_formatted_string(long long num) {
int choice;
string GROUP_SEP;
cout << "Choose digit separator (1) for comma, (2) for space, (3) for period: " << endl;
cin >> choice;
GROUP_SEP = determine_separator(choice);
//Read data into string s.
stringstream temp, out;
temp << num;
string s = temp.str();
//Write first characters, in front of
// first separator (GROUP_SEP).
int n = s.size() % GROUP_SIZE;
int i =0;
if (n > 0 && s.size() > GROUP_SIZE) {
out << s.substr(i, n) << GROUP_SEP;
i += n;
}
// Handle all the remaining groups.
n = s.size() / GROUP_SIZE -1;
while (n-- > 0) {
out << s.substr(i, GROUP_SIZE) << GROUP_SEP;
i += GROUP_SIZE;
}
out << s.substr(i); //Write the rest of digits.
return out.str(); //Convert stream -> string.
}
string determine_separator(int choice){
switch(choice){
case 1:
return ",";
break;
case 2:
return " ";
break;
case 3:
return ".";
break;
}
}