如果单词"退出"如何在命令promt中退出?打字?

时间:2017-04-19 18:32:43

标签: c++

我必须编写一个程序,要求用户在命令提示符下键入一个句子。如果用户输入了单词"退出"或"退出" (没有引号和所有小写),然后程序应该退出。否则,程序应该打印用户键入的内容并要求用户输入其他内容。我理解如何获得句子,但我不知道如何让程序退出命令提示符。请帮忙吗?

#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;
}

2 个答案:

答案 0 :(得分:3)

您可以将值接收数据与“退出”进行比较。 如果您只想显示类型,请返回用户数据,请尝试以下操作:

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;
}

如果您想在键入“exit”时输入回输,请尝试以下操作:

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;
}

答案 1 :(得分:1)

您可以尝试以下代码:

#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;
    }
}