Mengapa keluaran saya tidak menampilkan jawaban yang benar

pemrograman

[ad_1]

oke misalkan saya membuat file input yang berisi kata dan artinya. jadi saya mengizinkan pengguna menanyakan kata yang ingin mereka cari. Misalnya pengguna ingin mencari kata ‘waktu’, maka kata ‘waktu’ ada di file masukan dan artinya akan ditampilkan ke terminal.
tetapi mengapa output saya menunjukkan bahwa kata ‘waktu’ tidak ditemukan sedangkan kata ‘waktu’ ada di file input.

Apa yang saya coba:

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;
}

Solusi 1

Kode berikut

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";
}

berfungsi di kotak Linux saya, asalkan file input terstruktur dengan benar (yaitu satu baris utuh untuk file apa pun kata diikuti oleh seluruh baris untuk definisi kata; misalnya, saya dict.txt adalah

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

[ad_2]

コメント

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