从文件中读取单词

时间:2021-02-05 13:34:28

标签: c

我得到了一个 txt 文件,里面有单词和它们的定义,中间有分号和不同的空格,每个单词都在新行中有定义。看起来像这样:

我得到了一个代码,但我不知道如何从文件中读取然后按字母搜索。感谢您的帮助。

我得到了一个代码,但我不知道如何从文件中读取然后按字母搜索。感谢您的帮助。

#include <iostream>
#include <string>
#include <fstream> 

using namespace std;

int main(){
    ifstream input;
    input.open("dictionary.txt"); 

    if(!input.is_open()){
        cout << "Error" << endl;
    } 

    else{
        char ch;
        string str; 

        for (int i = 0; i < 3; i++){
                cout << "Reading file";
                cout << " " << i << endl;
                sleep(0);
                system("cls");
        } 

        cout << "File was open" << endl;
        sleep(0);
        cout.flush();
        system("cls"); 

        int choise;
        
        menu:
        cout << "1. Starting\n2. Containing\n3. Ending\n4. Stop\nInput your choise: ";
        cin >> choise;
        system("cls"); 

        switch(choise){
            case 1:{   // searching by 1 letter
                cout << "Input letter: "
                goto menu;
            } 

            case 2:{  // searching by any letter in word
                goto menu;
            } 

            case 3:{  // searching by last letter 
                 goto menu;
            } 

            case 4:{
                system("cls");
                cout << "Closing file" << endl;
                sleep(2);
                break;
            } 

            default:{
                cout << "Input 1-4!" << endl;
                goto menu;
            }
        }
    } 

    input.close();
}

2 个答案:

答案 0 :(得分:1)

这是一个如何解决您的问题的示例。我已经编写了字符串搜索代码、字典元素加载代码并重写了删除 goto 的输入循环。代码还是有问题,比如只加载了字典的3个元素。

#include <iostream>
#include <string>
#include <fstream> 
#include <unistd.h>
#include <vector>

using namespace std;

struct mydictionary
{
  string sDefinition;
  string sDescription;
};

void PrintByFirstLetter(const std::vector<mydictionary>& dict, char letter) {
    for (auto &istr: dict) {
        if( istr.sDefinition.length() && *istr.sDefinition.begin() == letter)
            cout << istr.sDefinition << " - " << istr.sDescription << endl;
    }
}

void PrintByLastLetter(const std::vector<mydictionary>& dict, char letter) {
    for (auto &istr: dict) {
        if( istr.sDefinition.length() && *(--istr.sDefinition.end()) == letter)
            cout << istr.sDefinition << " - " << istr.sDescription << endl;
    }
}

void PrintByAnyLetter(const std::vector<mydictionary>& dict, char letter) {
    for (auto &istr: dict) {
        //if (istr.sDefinition.find(letter) != istr.sDefinition.end())
        if (istr.sDefinition.find(letter) != std::string::npos)
            cout << istr.sDefinition << " - " << istr.sDescription << endl;
    }
}

int main(){
    ifstream input("dictionary.txt");

    if(!input.is_open()) {
        cout << "Failed to open dictionary" << endl;
    } 
    else {
        mydictionary mdc;
        std::vector<mydictionary> dict;

        for (int i = 0; i < 3; i++) {
                cout << "Reading file";
                cout << " " << i << endl;

                std::getline(input, mdc.sDefinition, ';');
                cout << mdc.sDefinition << endl;
                std::getline(input, mdc.sDescription);
                cout << mdc.sDescription << endl;
                dict.push_back(mdc);

                sleep(0);
                system("cls");
        } 

        cout << "File was open" << endl;
        sleep(0);
        cout.flush();
        system("cls");

        int choise;
        do
        {
            cout << "1. Starting\n2. Containing\n3. Ending\n4. Stop\nInput your choise: ";
            cin >> choise;
            system("cls"); 

            if(choise >= 1 && choise <= 3) {
                char letter;
                cout << "Input letter:";
                cin >> letter;
                if( choise == 1) // searching by 1 letter
                    PrintByFirstLetter(dict, letter);
                else if( choise == 2) // searching by any letter in word
                    PrintByAnyLetter(dict, letter);
                else if( choise == 3) // searching by last letter
                    PrintByLastLetter(dict, letter);
            }
            else if(choise == 4) {
                system("cls");
                cout << "Closing file" << endl;
                sleep(2);
                break;
            } 
            else
                cout << "Input 1-4!" << endl;
        } while(1);
    }
}

答案 1 :(得分:1)

您也可以使用正确的 C++ 代码来完成任务。

使用现代 C++ 元素和算法。

而且,尤其是通过真正使用所有 iostream 设施。

一个例子可能是:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <iterator>
#include <algorithm>
#include <limits>

struct TermDefinition {
    // The data
    std::string term{};
    std::string definition{};
    // Override extractor operator
    friend std::istream& operator >> (std::istream& is, TermDefinition& td) {
        std::getline(std::getline(is, td.term, ';') >> std::ws, td.definition);
        return is;
    }
    // Overwrite inserter operator
    friend std::ostream& operator << (std::ostream& os, const TermDefinition& td) {
        return os << td.term << " - " << td.definition;
    }
};

int main() {
    // Open file and check, if it could be opened
    if (std::ifstream dictionaryStream{ "dictionary.txt" }; dictionaryStream) {

        // Read complete file. Split it into components. Add to vector
        std::vector dictionary(std::istream_iterator<TermDefinition>(dictionaryStream), {});

        // As long as we should run the program, do the loop
        bool runProgram{ true };
        while (runProgram) {

            // Get teh election for the user. Check for errors in input
            std::cout << "\n\nMenu. Please select\n\n1 -> Starting\n2 -> Containing\n3 -> Ending\n4 -> Stop\n\nPlease enter 1 or 2 or 3 or 4: ";
            if (unsigned int selection{}; std::cin >> selection) {

                // Depending on selction gieven by user
                switch (selection) {
                case 1:
                    // Give instruction to user
                    std::cout << "\n\nSearching by first letter. Enter letter: ";

                    // Get one letter from user and check for valid input
                    if (std::string letter{}; std::getline(std::cin >> std::ws, letter) && letter.length() == 1)

                        // Copy all dictionary entries fullfilling the search criteria to std::cout
                        std::copy_if(dictionary.begin(), dictionary.end(), std::ostream_iterator<TermDefinition>(std::cout, "\n"), 
                            [&letter](const TermDefinition& td) { return *td.term.begin() == letter[0]; });
                    break;
                case 2:
                    // Give instruction to user
                    std::cout << "\n\nSearching by any letter. Enter letter: ";

                    // Get one letter from user and check for valid input
                    if (std::string letter{}; std::getline(std::cin >> std::ws, letter) && letter.length() == 1)

                        // Copy all dictionary entries fullfilling the search criteria to std::cout
                        std::copy_if(dictionary.begin(), dictionary.end(), std::ostream_iterator<TermDefinition>(std::cout, "\n"),
                            [&letter](const TermDefinition& td) { return td.term.find(letter[0]) != std::string::npos; });
                    break;
                case 3:
                    // Give instruction to user
                    std::cout << "\n\nSearching by last letter. Enter letter: ";

                    // Get one letter from user and check for valid input
                    if (std::string letter{}; std::getline(std::cin >> std::ws, letter) && letter.length() == 1)

                        // Copy all dictionary entries fullfilling the search criteria to std::cout
                        std::copy_if(dictionary.begin(), dictionary.end(), std::ostream_iterator<TermDefinition>(std::cout, "\n"),
                            [&letter](const TermDefinition& td) { return td.term.back() == letter[0]; });
                    break;
                case 4:
                    // User wants to stop the program
                    // Set loop flag to 0
                    runProgram = false;
                    std::cout << "\n\nDone. Exiting program . . .\n\n";
                    break;
                default:
                    std::cout << "\n\nInvalid number. Please try again\n\n";
                    break;
                }
            }
            else {
                std::cout << "\n\nError: Invalid input. Please try again\n\n\n";
                // Reset bad input state an consume nonesense characters
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
        }
    }
    else std::cerr << "\n\nError: Could not open input file!\n\n";
    return 0;
}

您已经接受了另一个答案。所以,我的猜测是你没有读过这篇文章,因此不需要进一步的解释。否则,请发表评论,我会添加说明。