c++ - out_of_bounds:基本字符串C++

标签 c++

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

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::replace: __pos (which is 4294967295) > this->size() (which is 12)

我的密码
#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;
}

最佳答案

这部分

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

是错误的,因为您在减去之后和检查之前正在使用i

添加检查将消除此问题。
while(i>=0){
    i -= 2;
    if (i > 0) numString = numString.insert(i,",");
}

关于c++ - out_of_bounds:基本字符串C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61563950/

相关文章:

c++ - boost fusion/MPL : convert type from sequence to sequence of equivalent any_range's

c++ - XML/C++ 类型绑定(bind)出错

c++ - 无法对 unordered_set 进行排序

c++ - 在编译时复制 C/C++ 函数

c++ - BOOST 线程 : cout behavior

c++ - 在字符串中查找随机排序的子字符串

java - 使用图表 X 的 VC++ 图表

C++ 禁用静态变量的析构函数

c++ - AFT(缩写函数模板)有什么争议?

c++ - 初始化字符串时额外的大括号