Ctrl+Z无法在循环时退出

Ctrl + Z not working to exit while loop

本文关键字:退出 循环 Ctrl+Z      更新时间:2023-10-16

我一直在四处寻找并尝试了很多方法,但我一辈子都无法让Ctrlz退出控制台。这是我的代码,有人能告诉我正确的方向吗:

这是在Windows上。

int main()
{
    string s;
    Stack *stack = new Stack();
    while (cin >> s)
    {
        if (cin)
        {
            for (int i = 0; i < (int)s.length(); i++)
            {
                stack->push(s[i]);
            }
            for (int i = 0; i < s.length(); i++)
            {
                cout << stack->top();;
                stack->pop();
            }
            cout << endl;
        }
    } 
    stack->~Stack();
    delete stack;
    return 0;
}

在Windows上,按Ctrl-Z以发出EOF信号。在Linux上,它是Ctrl-D。在任何一个系统上,您都需要在行首按下它(即,在按下回车键后)。

顺便说一下,没有必要显式调用析构函数。去掉这条线:

stack->~Stack();

事实上,最好是完全去掉newdelete。这些闻起来像Java主义。在C++中,您不必总是使用new来创建新对象。更基本的语法是写:

Stack stack;

这将创建一个Stack对象,并调用默认的无参数构造函数。当main()退出时,对象将被自动销毁,因此您不需要delete或显式的销毁函数调用。

最后,if (cin)检查是多余的。while循环已经检查是否读取了字符串。

while (cin >> s)
{
    if (cin)
    {
        ...
    }
}

由于您使用的是内置堆栈,因此不需要使用。->并且如果(cin)或者作为都不需要,而(cin>>s)is检查用力流是否已到达终点。这是正确的代码。

#include <string>
#include <stack>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
     string s;
     stack <string> st;
     while (cin >> s)
     {
            st.push(s);
            cout << st.top();;
            st.pop();
            cout << endl;
      }
     st.~stack();
     return 0;

}