stack库中push()读取字符无效


#include <iostream>
#include <stack>
using namespace std;
int main() {
    stack<char> s;
    char info[1000] = {0};
    scanf("%s",info);
    for(int i = 0; i<sizeof(info); i++) {
        //判断是否为符号
        if(info[i]=='+'||info[i]=='-'||info[i]=='*'||info[i]=='/'||info[i]=='('||info[i]==')') {
            s.push(info[i]);
        }
    }
    printf("%c",s.top());

}

img


请大佬指教问题出在哪里

望采纳

您的代码中存在几个问题。

首先,您在读入字符串时使用了 scanf 函数。在这个函数中,您没有指定字符数组的长度,所以可能会导致缓冲区溢出,即在数组 info 中写入超出数组长度的数据。

为了避免这个问题,您可以使用 fgets 函数来读入字符串,并指定字符数组的长度。例如:

fgets(info, 1000, stdin);

其次,您在循环中使用了 sizeof 函数,并将它用作循环的终止条件。然而, sizeof 函数返回的是字符串数组的总字节数,而不是字符串的长度。所以,您的循环会一直执行,直到访问到数组的无效内存区域。

为了避免这个问题,您可以使用 strlen 函数来检查字符串的长度,并将它用作循环的终止条件。例如:

for (int i = 0; i < strlen(info); i++) {
    // 判断是否为符号
    if (info[i] == '+' || info[i] == '-' || info[i] == '*' || info[i] == '/' || info[i] == '(' || info[i] == ')') {
        s.push(info[i]);
    }
}

综上所述,下面是修改后的代码:

#include <iostream>
#include <stack>
#include <cstring>
using namespace std;

int main() {
    stack<char> s;
    char info[1000] = {0};
    fgets(info, 1000, stdin);
    for (int i = 0; i < strlen(info); i++) {
        // 判断是否为符号
        if (info[i] == '+' || info[i] == '-' || info[i] == '*' || info[i] == '/' || info[i] == '(' || info[i] == ')') {
            s.push(info[i]);
        }
    }
    printf("%c", s.top());
    return 0;
}