C++循环期间字符串大小会发生变化

C++ string size changing during loop

本文关键字:变化 循环 字符串 C++      更新时间:2023-10-16

我的程序假设读取一个字符串,然后将每个字符插入堆栈中。我注意到当我打印length时,这是单词的大小,它变成了一些高数字。例如:word = "hello"长度一开始将 = 5,但最终更改为 = 111 。此外,当我使用 2 个字母时,我总是遇到分段错误。是什么原因造成的?为什么单词的长度会发生变化?

#include <iostream>
#include <string>
#include "Stack.h"
using namespace std;
int main()
{
    Stack stack;
    string word;
    cout << "Enter word: ";
    getline(cin, word);
    cout << word << "|"  << endl;
    int length = word.size();
    for (int i = 0; i < length; i++) {
        cout << "i: " << i << "tlength: " << length << endl;
        stack.push(word[i]);
        cout << "TOP: "  << stack.top() << endl;
    }   

    while (!stack.isEmpty())
    {
        cout << stack.pop();
    }
    cout << endl;   
    return 0;
}

#include <iostream>
#include <string>
#define STACK_CAPACITY 1000
using namespace std;
class Stack
{
    private:
        int topIndex;
        char arr[];
    public:
        // Constructor
        Stack()
        {
            arr[STACK_CAPACITY];
            topIndex = -1;
        }
        // adds elements to "top" of array
        void push(char c)
        {
            // if stack is full, do not add
            if (isFull())
            {
                cout << "Push on full Stack" << endl;
                // terminate function
            }
            topIndex++;
            arr[topIndex] = c;
        }
        // Removes last inserted (push) element from the stack and returns it
        char pop()
        {
            // checks if Stack is empty
            if (isEmpty())
            {
                cout << "Pop on empty Stack" << endl;
                return '@';
            }
            // if not empty, remove and return last element inserted
            char temp = arr[topIndex];
            arr[topIndex--] = ' ';
            return temp;
        }
        // Returns but does not remove last inserted (push) element
        char top() { return arr[topIndex]; }
        // Utilities 
        bool isEmpty() { return topIndex == -1; } 
        bool isFull() { return topIndex == STACK_CAPACITY - 1; }
        int size() { return topIndex + 1; }
        // Destructor
        ~Stack() 
        {
        }
}

您的Stack类中存在各种问题,导致它表现出未定义的行为。

例如,在构造函数中

    Stack()
    {
        arr[STACK_CAPACITY];
        topIndex = -1;
    }

不会(我猜,您所期望的那样(调整arr大小以具有STACK_CAPACITY元素。 它试图评估arr[STACK_CAPACITY]的值,因为arr被声明为char arr[],所以不存在。 因此,该声明具有未定义的行为。

同样,push()成员函数

    // adds elements to "top" of array
    void push(char c)
    {
        // if stack is full, do not add
        if (isFull())
        {
            cout << "Push on full Stack" << endl;
            // terminate function
        }
        topIndex++;
        arr[topIndex] = c;
    }

尝试(在第一次调用时(修改arr[0] - 这也不存在。

当行为未定义时 - 如上文所示 - 任何事情都可能发生。 包括似乎覆盖不相关的数据或(在您的情况下(覆盖字符串word的部分内容 main() .

您需要更好地阅读C++的基础知识,而不是猜测事情是如何运作的。 你猜错了。