0

だから私は特定の.txtファイルで文字列を見つけるはずのコードを持っています。入力がファイルにある場合、「はい、見つかりました」と表示されますが、そうでない場合は「何も見つかりませんでした」と表示されます、しかし、そのステップをスキップして終了します。初心者ですので、明らかなミスがありましたら申し訳ありません。

#include <stdio.h>
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>


using namespace std;

int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;

ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
cin.get();
cout.flush();
Myfile.open("db.txt");


cin >> hledat;

if (Myfile.is_open())
{
    while (!Myfile.eof())
    {
        getline(Myfile, line);
        if ((offset = line.find(hledat, 0)) != string::npos)
        {
            cout.flush();
            cout << "Found it ! your input was  :   " << hledat << endl;
        }


    }
    Myfile.close();

}



else
{
    cout.flush();
    cout << "Sorry, couldnt find anything. Your input was   " << hledat << endl;
}

getchar();
system("PAUSE");
return 0;

}

4

2 に答える 2

0

3 つのケースが考えられます。

  1. ファイルが正常に開かれませんでした。
  2. ファイルは正常に開かれましたが、文字列が見つかりませんでした。
  3. ファイルは正常に開かれ、文字列が見つかりました。

ケース 1 と 3 のプリントアウトがありますが、2 はありません。

ところで、あなたのループ条件は間違っています。読み取り試行後の ostream オブジェクト自体である getline への呼び出しの結果を使用します。

while (getline(MyFile, line))
{
    ...
}

ループは、最後の行を読み取った後に発生する読み取り試行の失敗時に終了します。あなたが持っている方法では、最後の行の後に読み取ろうとしますが、これは失敗しますが、ループが最初からやり直すまで eof をチェックしないため、存在しない行を処理しようとします。

于 2013-10-31T20:46:02.800 に答える
0

コメントアウトするだけ//cin.get(); です。必要ありません。

出力:

Welcome, insert the string to find in the file.



apple
Found it ! your input was  :   apple

それ以外は、魅力のように機能します。

修正されたコード:

#include <stdio.h>

#include <iostream>
#include <fstream>
#include <string>


using namespace std;

int main(void)
{
    setlocale(LC_ALL, "");
    string hledat;
    int offset;
    string line;

    ifstream Myfile;
    cout.flush();
    cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
    //cin.get();   <-----  corrected code
    cout.flush();
    Myfile.open("db.txt");


    cin >> hledat;

    if (Myfile.is_open())
    {
        while (!Myfile.eof())
        {
            getline(Myfile, line);
            if ((offset = line.find(hledat, 0)) != string::npos)
            {
                cout.flush();
                cout << "Found it ! your input was  :   " << hledat << endl;
            }


        }
        Myfile.close();

    }



    else
    {
        cout.flush();
        cout << "Sorry, couldnt find anything. Your input was   " << hledat << endl;
    }

    getchar();
    system("PAUSE");
    return 0;

} 
于 2013-10-31T21:03:29.090 に答える