c++ - 按字母顺序从文件中返回单词
问题描述
我正在尝试在春假期间进行一点自学,我创建了一个程序,该程序将接受单词将它们存储在一个文件中,然后将它们打印到控制台。我正在寻找按字母顺序而不是按输入顺序打印它们的最佳方法。我已经在网上看到了一些关于如何使用矢量来执行此操作的示例,但我们还没有在课堂上真正触及到这一点,所以我想知道是否有一种方法可以不使用矢量来做到这一点?
到目前为止,这就是我所拥有的,将输入存储在文件中,直到输入“退出”,然后它会将单词打印回我正在使用的控制台,using namespace std;
为了简单起见,我知道大多数人认为这是不好的做法。谢谢你的帮助。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
string input;
ofstream file;
file.open("words.txt");
while(input != "quit"){
cin >> input;
file << input << std::endl;
if(input == "quit"){
file.close();
}
}
fstream dataFile("words.txt", ios::in);
if(dataFile.fail())
{
cout << "Error opening File..." << endl;
return 0;
}
while(dataFile >> input)
{
cout << input << std::endl;
}
dataFile.close();
return 0;
}
解决方案
向量是可变大小的同质容器。它是您应该使用的默认容器,前提是您所做的工作没有特殊要求。
如果将单词放在 astd::vector
中,则可以使用std::sort()
它按字母顺序对其进行排序。这是一个例子:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> words {"this", "is", "an", "example"};
std::sort(words.begin(), words.end());
for(auto const & word : words)
std::cout << word << '\n';
}
用尤达的话说,这将打印以下内容:
an
example
is
this
用输入文件中的单词填充向量应该不难。
推荐阅读
- javascript - 选择 iframe 内的元素返回空数组
- java - Cassandra -f 找不到依赖库 java.lang.UnsatisfiedLinkError
- python - 搜索 json 文件返回数据框列中键的一部分
- bash - 如何在bash中忽略diff的输出
- r - 使用 R 中另一个数据框的值在数据框中创建一列
- sql - SQL Server 从两个表中获取多行数据
- awk - 使用来自 FILE_2 和 bash 的匹配键的值将值更新到 FILE_1 - 也许是 awk
- c# - Asp.Net Core 如何将迁移类型配置为程序集
- asp.net-web-api - 如何使用 ASP.NET Web API 应用程序和 IIS Express 重现超时错误
- excel - Excel如何将日期转换为文本?