简体   繁体   中英

C++ An invalid parameter was passed to a function that considers invalid parameters fatal

So, I am trying to write a program that will eventually create a 2D array that will contain the location of mathematical operators in a user input string. so, for example, if the user put in 2+5-3, I want my array to be something like {{+,1}{-,3}}. I intended to just use an integer array and a known translation from +,-,/,*,^ to 1,2,3,4,5 respectively. however I keep getting an exception thrown when I try to test it saying "string subscript out of range" and then my IDE puts up an error code on my if statement that reads "An invalid parameter was passed to a function that considers invalid parameters fatal". Any Ideas where I've messed up?

#include <iostream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <climits>

using namespace std;


int main()
{
equationstart:
    string eq;
    int posOp[50][2];
    int i;
    int i2 = 0;
    int i3;

    getline(cin, eq);
    for (i = 0; i <= 49; i++) {
        if (eq[i] == '+') {
            posOp[i2][0] = 1;
            posOp[i2][1] = i;
            i2++;
        }
    }

    for (i = 0; i <= 49; i++) {
        for (i3 = 0; i3 <= 1; i3++) {
            cout << posOp[i][i3];
        }
        cout << endl;
    }

    cout << endl;
    goto equationstart;

}

right now all I want it to do is fill the array then display the acquired array to the screen so I can see that it is working.

a) please don't use C arrays posOp[50][2] . Use std::vector instead. It comes with range checking, if you use posOp.at(idx). std::vector is one of the most basic and most important C++ features.

b) As @drescherjm pointed out in the comments above, eq[i] will trigger an exception (fortunately), when eq.size() is less than 50. Your loop runs from 0 to 49, which is fine for posOp , but eq may be shorter. You are accessing eq beyond it's end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM