Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

c - Read word from file

I got a txt file with words and them definitions, with semicolon and different space between, also every word with definition in new line. It looks like that:

I got a code, but I don't know how to read from file and then search by letter. Thanks for your help.

I got a code, but I don't know how to read from file and then search by letter. Thanks for your help.

#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
2. Containing
3. Ending
4. Stop
Input 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();
}
question from:https://stackoverflow.com/questions/66064222/read-word-from-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could also use correct C++ code to do the task.

With modern C++ elements and algorithms.

And, especially, by really using all iostream facilities.

One example could be:

#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 << "

Menu. Please select

1 -> Starting
2 -> Containing
3 -> Ending
4 -> Stop

Please 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 << "

Searching 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, "
"), 
                            [&letter](const TermDefinition& td) { return *td.term.begin() == letter[0]; });
                    break;
                case 2:
                    // Give instruction to user
                    std::cout << "

Searching 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, "
"),
                            [&letter](const TermDefinition& td) { return td.term.find(letter[0]) != std::string::npos; });
                    break;
                case 3:
                    // Give instruction to user
                    std::cout << "

Searching 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, "
"),
                            [&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 << "

Done. Exiting program . . .

";
                    break;
                default:
                    std::cout << "

Invalid number. Please try again

";
                    break;
                }
            }
            else {
                std::cout << "

Error: Invalid input. Please try again


";
                // Reset bad input state an consume nonesense characters
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '
');
            }
        }
    }
    else std::cerr << "

Error: Could not open input file!

";
    return 0;
}

You already accepted the other answer. So, my guess is that you do no read this and therefore do not need further explanations. Otherwise, please comment and I will add explanations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...