将string转换为stack-int-value,当为负数时,会产生奇怪的值

Conversion of string to stack-int-value, when is negative, results in strange value

本文关键字:转换 string stack-int-value      更新时间:2023-10-16

我试图在堆栈中转换我的数字字符串,但我不明白为什么当数字为负时,第一个元素总是-3

void Soma::StrToInt(char str1[], char str2[]) {
    for (int i = 0; str1[i] != ''; i++) {
        if (str1[0] == '-') {              //if is negative
            negative1 = true;
        }
        p1.push(str1[i] - '0');
        cout << p1.top() << endl;//Always showing the first element == -3
    }
    for (int i = 0; str2[i] != ''; i++) {
        if (str1[0] == '-') {
            negative2 = true;
        }
        p2.push(str2[i] - '0');
    }
}

完整的代码太大了,不能在这里发布,问题是为什么这个-3值出现,当我的字符串是负的,像-500, -9514897654654或任何负数。

最小版本:

int main() {
    char str1[] = { '-','4','0','0' };
    stack<int> p1;
    for (int i = 0; str1[i] != ''; i++) {
        p1.push(str1[i] - '0');
        cout << p1.top() << endl;
        p1.pop();
    }
}     

这里的问题是,p1.push(str1[i] - '0');正试图从'-'减去'0',如果字符串持有一个负数,因为你总是从i = 0开始。您需要做的是在循环之前检查字符串是否为负,然后根据该检查从01开始。比如

void Soma::StrToInt(char str1[], char str2[]){
    int start = 0;
    if(str1[0] == '-'){              //if is negative
        negative1 = true;
        start = 1;
    }
    for(int i=start; str1[i]!=''; i++)
    //...
}

现在,如果字符串是负的,您将跳过字符串中的'-',只推入数字。