Tại sao đầu ra của tôi không hiển thị câu trả lời đúng

lập trình


được rồi, giả sử tôi đã tạo một tệp đầu vào có chứa từ và nghĩa của nó. vì vậy tôi cho phép người dùng hỏi từ mà họ muốn tìm kiếm. ví dụ: người dùng muốn tìm kiếm từ ‘thời gian’, vì vậy từ ‘thời gian’ có trong tệp đầu vào và ý nghĩa của nó sẽ được hiển thị trên thiết bị đầu cuối.
nhưng tại sao đầu ra của tôi hiển thị rằng không tìm thấy từ ‘thời gian’ trong khi từ ‘thời gian’ có trong tệp đầu vào.

Những gì tôi đã thử:

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

Giải pháp 1

Đoạn mã sau

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

hoạt động trên hộp Linux của tôi, miễn là tệp đầu vào có cấu trúc chính xác (đó là toàn bộ dòng cho bất kỳ từ theo sau là cả một dòng cho định nghĩa từ; ví dụ như tôi 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をコピーしました