Pourquoi ma sortie n’a pas affiché la bonne réponse

la programmation


ok, disons que j’ai créé un fichier d’entrée qui contient le mot et sa signification. je permets donc à l’utilisateur de demander le mot qu’il souhaite rechercher. par exemple, l’utilisateur souhaite rechercher le mot « heure », donc le mot « heure » est dans le fichier d’entrée et sa signification sera affichée sur le terminal.
mais pourquoi ma sortie montre que le mot « temps » n’est pas trouvé alors que le mot « temps » contient dans le fichier d’entrée.

Ce que j’ai essayé :

C++
case 2: {
    string searchWord;
    cout << "Enter the word to search: ";
    cin >> searchWord;

    bool found = false;

    string word, meaning;
    while (getline(inFile, word) && getline(inFile, meaning)) {
        if (searchWord == word) {
            char firstAlphabet = searchWord.at(0);
            cout << "Word " << searchWord << " found in the dictionary.\n\n";
            cout << lineNum++ << "\t" << firstAlphabet << "\t" << searchWord << "\t" << meaning << endl;
            found = true;
            break;
        }
    }

    if (!found) {
        cout << "Word " << searchWord << " not found in the dictionary.\n";
    }

    cout << "\nDone...\n";
    break;
}

Solution 1

Le code suivant

C++
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    string searchWord;
    cout << "Enter the word to search: ";
    cin >> searchWord;

    bool found = false;

    ifstream inFile("dict.txt");

    string word, meaning;
    size_t itemNum = 0;
    while (getline(inFile, word) && getline(inFile, meaning))
    {
        if (searchWord == word) {
            char firstAlphabet = searchWord.at(0);
            cout << "Word " << searchWord << " found in the dictionary.\n\n";
            cout << (itemNum+1) << "\t" << firstAlphabet << "\t" << searchWord << "\t" << meaning << endl;
            found = true;
            break;
        }
      ++itemNum;
    }

    if (!found) {
        cout << "Word " << searchWord << " not found in the dictionary.\n";
    }

    cout << "\nDone...\n";
}

fonctionne sur ma machine Linux, à condition que le fichier d’entrée soit correctement structuré (c’est-à-dire une ligne entière pour n’importe quel mot suivi d’une ligne entière pour le définition de mot; par exemple, mon dict.txt est

money
a current medium of exchange in the form of coins and banknotes
time
the indefinite continued progress of existence and events in the past, present, and future regarded as a whole
universe
all existing matter and space considered as a whole

コメント

タイトルとURLをコピーしました