如何让我的程序在键入"exit"后打印用户键入的所有数据
How do I make my program print all data typed by user after "exit" is typed
这是我给予的分配:
编写一个程序,该程序反复要求用户输入句子,然后按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>
。有关此功能的更多信息,请检查此链接。
相关文章:
- 打印时有二叉树问题.用户输入不打印任何内容
- 我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出
- 使用用户输入打印 6X10 矩阵的代码 - C++
- 我如何使它,无论用户用空白字符串按 Enter 多少次,它总是打印"开始"字符串?
- :CIN 不断打印用户在每次循环后输入的内容
- 读取一组用户输入,按升序排序,然后打印结果
- 从用户那里获得无限量的输入,而不是打印最大的3个,而不使用数组
- 如何在没有打印语句的情况下报告用户输入错误
- 无法打印用户填充的部分数组的反面
- 如何实现否定用户输入退出程序和打印列表?
- 有没有更简单的方法可以从用户那里获取三个数字并按升序打印它们?
- 如何打印其值和尺寸由用户设置的数组
- 它不会打印出基于用户输入 c++ 输入的任务
- 如何让我的程序在键入"exit"后打印用户键入的所有数据
- 使用用户输入(无矢量)从 For 循环打印图表
- C++ 准确打印用户输入的内容
- 数组 1D 我需要要求用户检查索引和打印值
- 如何打印用户在C++中输入的 10 个数字的最小值
- 如何使用 std::copy 打印用户定义的类型
- 我在C++从函数中的用户获取输入、添加到数组和打印该数组时遇到问题