如何让我的程序在键入"exit"后打印用户键入的所有数据

How do I make my program print all data typed by user after "exit" is typed

本文关键字:用户 打印 数据 exit 程序 我的      更新时间:2023-10-16

这是我给予的分配:

编写一个程序,该程序反复要求用户输入句子,然后按Enter。您的程序将将用户类型的每个句子存储到某个容器中。当用户键入"退出"或"退出"时,请按字母顺序将每个句子打印回屏幕,然后退出。

以下是我到目前为止所拥有的:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() 
{
    string data;
    vector 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 != "exit" && data != "Exit" )
        {
            // then type back
            cout << data << endl;
        }
    }
    while (data != "exit" && data != "Exit");
    return 0;
}

您需要遵循给出的指示:

编写一个程序,该程序反复要求用户输入句子,然后按Enter。您的程序将将用户类型的每个句子存储在某些容器中。当用户键入"退出"或"退出"时,请按字母顺序将每个句子打印回屏幕,然后退出。

您不会在任何地方存储句子,因此您无法对它们进行排序。您需要做更多这样的事情:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() 
{
    string line;
    vector<string> data;
    do
    {
        cout << "Type a sentence and press enter." << endl;
        cout << "If the word 'exit' is typed, the program will close." << endl;
        if (!getline(cin, line))
            break;
        // validate if data is equal to "exit"
        if ((line == "exit") || (line == "Exit"))
            break;
        data.push_back(line); // <-- ADD THIS!!
    }
    while (true);
    // sort the data alphabetically
    sort(data.begin(), data.end()); // <-- ADD THIS!!
    // then type it back out
    for(vector<string>::iterator i = data.begin(); i != data.end(); ++i) {
        cout << *i << endl;
    }
    return 0;
}

在寻找某种类型的排序功能时,我建议使用std:sort(),因为它是针对C++创建的。您可以使用qsort(),但不要因为它在C上。

std:sort()函数的作用是按升序排列的一系列元素,这就是您想要的。使用此功能时要使用的标头是#include <algorithm>。有关此功能的更多信息,请检查此链接。