C++ 越界:基本字符串C++;

C++ 越界:基本字符串C++;,c++,C++,我必须做一个程序,从命令行获取参数,并使用公式a(I)*x^(I)计算N个元素的总和。命令行中的参数按以下顺序排列:x、n、A0…An。函数polynom()有效,但函数PrettyPrint()无效。它的目的是通过将双精度转换为字符串并放置“,”来放置1000个分隔符。调试程序后,变量numString的值是我期望的值,但是,当我尝试打印它时,我得到以下错误消息:(我还在另一个编译器上尝试了该代码,并得到了相同的结果) 我的代码 #include <iostream> #inclu

我必须做一个程序,从命令行获取参数,并使用公式a(I)*x^(I)计算N个元素的总和。命令行中的参数按以下顺序排列:x、n、A0…An。函数
polynom()
有效,但函数
PrettyPrint()
无效。它的目的是通过将双精度转换为字符串并放置“,”来放置1000个分隔符。调试程序后,变量
numString
的值是我期望的值,但是,当我尝试打印它时,我得到以下错误消息:(我还在另一个编译器上尝试了该代码,并得到了相同的结果)

我的代码

#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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
双多项式(向量表){
//ToDo:练习2.b-计算P(x)的值
双结果=0;
int i=0;
而(i

while(i>=0){
    i -= 2;
    numString = numString.insert(i,",");
}
是错误的,因为您在减法之后和检查之前使用了
i

添加检查将消除该问题

while(i>=0){
    i -= 2;
    if (i > 0) numString = numString.insert(i,",");
}
while(i>=0){
    i -= 2;
    if (i > 0) numString = numString.insert(i,",");
}