首页 > 解决方案 > 按字母顺序从文件中返回单词

问题描述

我正在尝试在春假期间进行一点自学,我创建了一个程序,该程序将接受单词将它们存储在一个文件中,然后将它们打印到控制台。我正在寻找按字母顺序而不是按输入顺序打印它们的最佳方法。我已经在网上看到了一些关于如何使用矢量来执行此操作的示例,但我们还没有在课堂上真正触及到这一点,所以我想知道是否有一种方法可以不使用矢量来做到这一点?

到目前为止,这就是我所拥有的,将输入存储在文件中,直到输入“退出”,然后它会将单词打印回我正在使用的控制台,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;
}

标签: c++

解决方案


向量是可变大小的同质容器。它是您应该使用的默认容器,前提是您所做的工作没有特殊要求。

如果将单词放在 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

用输入文件中的单词填充向量应该不难。


推荐阅读