如果键入了单词 "exit",如何在命令 promt 中进行此退出?

How do i make this exit in the command promt if the word "exit" is typed?

本文关键字:promt 命令 退出 单词 exit 如果      更新时间:2023-10-16

我必须编写一个程序,要求用户在命令提示符中输入句子。如果用户键入"退出"或"退出"一词(没有引号和所有较低的情况(,则该程序应退出。否则,程序应打印用户键入屏幕的内容,并要求用户键入其他内容。我了解如何获取句子,但我不知道如何使程序退出命令提示符。请帮助?

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string data;
    cout << "Type a sentence and press enter."
        "If the word 'exit' is typed, the program will close." << endl;
    getline(cin, data);
    cout << data;

    return 0;
}

您可以将接收数据与"退出"进行比较。如果您只需显示输入用户数据,请尝试以下操作:

int main() {
    string data;
    cout << "Type a sentence and press enter."
            "If the word 'exit' is typed, the program will close." << endl;
    getline(cin, data);

    // validate if data is equals to "exit"
    if (data.compare("exit") != 0) {
        cout << data;
    }
    return 0;
}

如果要在输入"退出"时输入输入输入,请尝试以下操作:

int main() {
    string data;
    do {
        cout << "Type a sentence and press enter."
                "If the word 'exit' is typed, the program will close." << endl;
        getline(cin, data);
        // validate if data is not equals to "exit"
        if (data.compare("exit") != 0) {
            // then type back
            cout << data  << endl;
        } else {
            // else interrupt while
            break;
        } 
    // will run while break or return be called
    } while (true);
    // terminate the program
    return 0;
}

您可以尝试以下代码:

#include <iostream>
#include <cstdlib>
#include <boost/algorithm/string.hpp>
using namespace std;
int main() {
    string data;
    while(true) {
    cout << "Type a sentence and press enter."
        "If the word 'exit' is typed, the program will close." << endl;
    getline(cin, data);
    if ( boost::iequals(data, "exit") ) 
        exit(0);
    else 
        cout << data;
    }
}