0

次のセクションに問題があります。この特定の部分では、次のことを行う必要があります。選択した講師が教えたすべてのモジュールを一覧表示する

ユーザーからの入力とテキストファイルのデータの一致の一部に苦労しており、選択した講師が教えたモジュールのリストのみを表示します。

Taught.txtというテキストファイルがあり、テキストファイルの内容は次のとおりです。

IS1S01  AW 
IS1S02  MG 
SE2S552 BM 
CS2S504 BM 
CS3S08  SL 
MS3S28  DJ
CS1S03  EM 
BE1S01  SJ 
BE2S01  SH 
SS1S02  AB 
SE1S02  AW

以下のセクションは、私がこれまでに行ったコードです。

void listofmodulebylecturer()
{
    std::string Lecturer;
    std::string Module;

    // Display message asking for the user input
    std::cout << "\nList all modules taught by selected lecturers." << std::endl;
    std::cout << "Enter your preferred lecturers." << std::endl;

    // Read in from the user input
    std::cin >> Lecturer;

    // Read from text file and Display list of modules taught by the selected lecturer

    std::ifstream infile;

    // infile.open("Lecturer");
    infile.open("Taught.txt");

    if (!infile)
    {
        std::cout << "List is empty" << std::endl;
    }
    else
    {
        std::cout << "\nList of Modules:" << std::endl;

        while(!infile.eof())
        {
            getline(infile,Module);

            std::cout << Module << std::endl;
        }

        std::cout << "End of list\n" << std::endl;
    }

    infile.close();         // close the text file  
    system ("PAUSE");
}

使うことを考えていました

if (........)
{
}
else

それがうまくいくかどうか疑問に思いますか?

4

2 に答える 2

1

使いinfile.eof()たい用途に確実に使えるとは限りません。2 つの単語を読み、2 番目の単語が予想と一致する場合は最初の単語を出力する必要があります。単語を読むと、次のようになります。

for (std::string module, teacher; infile >> module >> teacher; ) {
    // check if the teacher is the correct one and, if so, print the module
}

...そして、はい、これにはifステートメントが機能します。

于 2012-12-12T22:44:13.977 に答える
0

各行には2つの文字列しか含まれていないため、使用しませんgetline()が、これは次のとおりです。

std::string course, teacher;

while (infile) {
    infile >> course >> teacher;
    if (infile) { // strings read correctly
        if (teacher == Lecturere) {
         ...
        }
    }
}
于 2012-12-12T22:54:17.140 に答える