簡體   English   中英

C++ 一個無效參數被傳遞給一個認為無效參數致命的 function

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

因此,我正在嘗試編寫一個程序,該程序最終將創建一個二維數組,該數組將包含用戶輸入字符串中數學運算符的位置。 因此,例如,如果用戶輸入 2+5-3,我希望我的數組類似於 {{+,1}{-,3}}。 我打算只使用 integer 數組和從 +,-,/,*,^ 到 1,2,3,4,5 的已知翻譯。 但是,當我嘗試測試它說“字符串下標超出范圍”時,我不斷拋出異常,然后我的 IDE 在我的 if 語句上放置一個錯誤代碼,內容為“無效參數已傳遞給認為無效參數致命的 function ”。 我搞砸的任何想法?

#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;

}

現在我想做的就是填充數組,然后將獲取的數組顯示到屏幕上,這樣我就可以看到它正在工作。

a) 請不要使用 C arrays posOp[50][2] 改用 std::vector 。 如果您使用 posOp.at(idx),它會進行范圍檢查。 std::vector 是 C++ 最基本和最重要的特性之一。

b)正如@drescherjm 在上面的評論中指出的那樣,當 eq.size() 小於 50 時, eq[i]將觸發異常(幸運的是)。您的循環從 0 運行到 49,這對於posOp來說很好,但是eq 可能會更短。 您正在訪問 eq 超出它的結尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM