I am trying to add commas to a set of numbers in an array.
I have a program that will take in random numbers the length of which are determined by the user's input. These numbers are stored in a pointer array. I made another array to store the converted numbers from int to string. Now I am working on a function to add commas to them. I am having an issue with this function. infoArrayString is the converted numbers of user input from int to string. The issue is in the addCommas function
#include <iostream>
#include <string>
using namespace std;
void validNumber(int & x){
while (cin.fail()){
cout << "ERROR: must be a number, try again ->";
cin.clear();
cin.ignore(1000, '\n');
cin >> x;
}
}
void validNumberPointer(int *& x){
while (cin.fail()){
cout << "ERROR: must be a number, try again ->";
cin.clear();
cin.ignore(1000, '\n');
cin >> *x;
cout << endl;
}
}
void amount(int & userAmount, const int & MIN_INPUT, const int & MAX_INPUT)
{
/*
* Asks how many number they want
*/
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
/*
* check
*/
validNumber(userAmount);
while ((userAmount < MIN_INPUT) or (userAmount > MAX_INPUT)){
cout << "ERROR: number out of range" << endl;
cout << "Please enter numbers in range of " << MIN_INPUT << " to " << MAX_INPUT << " ->";
cin >> userAmount;
}
}
void getInfo(int *& infoArray, int & userAmount){
for(int i = 0; i < userAmount; i++){
cout << "Input number #" << i+1 << " ->";
cin >> *(infoArray+i);
cout << endl;
/*
* check
*/
validNumberPointer(infoArray);
while (*(infoArray+i) < 0){
cout << "ERROR: number out of range" << endl;
cout << "Please enter numbers in range of range -> ";
cin >> *(infoArray+i);
cout << endl;
}
}
}
void convertString(int *& infoArray, string *& infoArrayString, int & userAmount){
for(int i = 0; i < userAmount; i++){
*(infoArrayString +i) = to_string(*(infoArray+i));
}
}
void addCommas(string *& infoArrayString){
for(int i = 0; i < infoArrayString[i].length(); i++){
if(i%3 == 0 and i != 0){
infoArrayString[i] = infoArrayString[i] + ",";
}
}
}
void displayBoard(string *& infoArrayString, int & userAmount){
cout << "The sum of: " << endl;
for(int i = 0; i < userAmount; i++){
cout << *(infoArrayString++) << endl;
}
}
int main() {
const int MIN_INPUT = 2, MAX_INPUT = 11;
int userAmount = MIN_INPUT;
int * infoArray = NULL;
infoArray = new int [MAX_INPUT];
string * infoArrayString = NULL;
infoArrayString = new string [MAX_INPUT];
amount(userAmount, MIN_INPUT, MAX_INPUT);
getInfo(infoArray, userAmount);
convertString(infoArray,infoArrayString,userAmount);
addCommas(infoArrayString);
displayBoard(infoArrayString, userAmount);
}