如何使C ++程序退出

时间:2015-05-18 22:45:25

标签: c++ exit

我正试图让我的C ++程序退出。

我知道我可以暂停while cin >> s的输入,但我不知道如何让整个程序退出。

这是我的代码:

int main()
{
    long int l;
    long int i;

    char s[100000];

    while (cin >> s)
    {
        l = strlen(s);//strlen Returns the length of the C string str. 


        for (i = 0; i<l; i++)
        {
            switch (s[i])
            {
            case 'W':
                cout << "Q";    break;
            case 'E':
                cout << "W";    break;
            case 'R':
                cout << "E";    break;
            default:
                cout << ";";    break;
            }

        }
        cout << (" ");
    }

    system("pause");

    return 0;
}

3 个答案:

答案 0 :(得分:3)

您的程序将在输入用尽时终止。

system("pause");似乎暗示您正在使用Microsoft Windows。要在Windows上发出键盘输入的文件结束信号,请键入 Ctrl-Z 。 (对于Linux和其他类Unix系统,请在行的开头使用 Ctrl-D 。)

顺便提一下,您发布的程序已完成,无法编译。这可以通过在顶部添加以下行来纠正:

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

发布问题时,请包含整个程序。

答案 1 :(得分:0)

我能够在while循环中使用命令include iostream include string using namespace std; int main(){ long int l; long int i; char s[100000]; cout << "\n Write your code in UpperCase, " cout << "to close the program switch to LowerCase \n" << endl; while (cin >> s) { l = strlen(s);//strlen Returns the length of the C string str. for (i = 0; i<l; i++) { switch (s[i]) { case 'W': cout << "Q"; break; case 'E': cout << "W"; break; case 'R': cout << "E"; break; default: exit(0); break; } } cout << (" "); } system("pause"); return 0; } 让程序退出。

这是我完成的程序:

{{1}}

答案 2 :(得分:-1)

您的循环正在等待cin >> s返回“文件结束”(EOF)。您可以通过键入 Ctrl + Z 或在类似Unix的系统(如Mac和Linux Ctrl + D )上在Windows上完成此操作。

您也可以在循环中放置一个中断字符,或者完全改变条件。