Reputation: 143
I have to do a program, that takes parameters from the command line and makes the sum of N elements using the formula A(i)*x^(i). The Parameters from the command line are in the following sequence: x, n, A0....An. Function polynom()
works, but function PrettyPrint()
doesn't. It's purpose is to put a thousand separator by converting a double to a string and putting ",". After debugging the program, the value of the variable numString
is what I expect it to be, however, when I tried to print it I get the following error message: (I also tried the code on another compiler and got the same result)
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace: __pos (which is 4294967295) > this->size() (which is 12)
My code
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <stdlib.h>
using namespace std;
double polynom(vector<double> list) {
// ToDo: Exercise 2.b - compute value of P(x)
double result = 0;
int i=0;
while(i<=list[1]){
result = result + (list[2+i] * pow(list[0],i));
//cout<<list[i];
i++;
}
return result;
}
void prettyPrint(double decimal)
{
// ToDo: Exercise 2.c - print number with thousands separators to console
int count = 0;
double decimal1 = decimal;
while(decimal1>1){
count++; //find how many digits are before the .
decimal1 = decimal1/10;
}
cout<<count<<endl;
string numString = to_string(decimal);
cout<< numString[count-1]<<endl;
int i = count-1;
while(i>=0){
i -= 2;
numString = numString.insert(i,",");
}
cout<<numString;
//std::cout << decimal;
}
int main(int argc, char* argv[])
{
// ToDo: Exercise 2.a - read parameters and x, deal with invalid values
// ToDo: Exercise 2.b - print P(x)
// ToDo: Exercise 2.c - print P(x) with prettyPrint
vector<double> list;
for ( int i = 1 ; i < argc ; i++){
double tmp (stod(argv[i]));
list.push_back(tmp); // add all arguments to the vector
}
if(list[1] < 1 || list[list.size()-1] == 0){
cout<<"invalid arguments"<<endl; //terminate program if the arguments are not acceptable
exit(1);
}
cout<<polynom(list)<<endl;
prettyPrint(polynom(list));
std::cout << "Hello World";
return 0;
}
Upvotes: 1
Views: 133
Reputation: 75062
This part
while(i>=0){
i -= 2;
numString = numString.insert(i,",");
}
is wrong because you are using i
after subtracting and before checking.
Adding checking will eliminate the problem.
while(i>=0){
i -= 2;
if (i > 0) numString = numString.insert(i,",");
}
Upvotes: 1