لماذا لم يعرض مخرجاتي الإجابة الصحيحة


حسنًا لنفترض أنني قمت بإنشاء ملف إدخال يحتوي على الكلمة ومعناها. لذلك أسمح للمستخدم أن يسأل عن الكلمة التي يريد البحث عنها. على سبيل المثال، يريد المستخدم البحث عن كلمة “الوقت”، لذا فإن كلمة “الوقت” موجودة في ملف الإدخال وسيتم عرض معناها على الجهاز.
ولكن لماذا يُظهر مخرجاتي أنه لم يتم العثور على كلمة “الوقت” بينما تحتوي كلمة “الوقت” على ملف الإدخال.

ما حاولت:

سي ++
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;
}

الحل 1

الكود التالي

سي ++
#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";
}

يعمل على صندوق Linux الخاص بي، بشرط أن يكون ملف الإدخال منظمًا بشكل صحيح (وهذا يمثل سطرًا كاملاً لأي ملف كلمة متبوعًا بخط كامل لـ تعريف الكلمة; على سبيل المثال، بلدي dict.txt يكون

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をコピーしました