3

C++ クラス用のプログラムを作成しています。最終的には、次の形式の連絡先のテキスト ファイルに対してプログラムでクイック ソートを実行する必要があります。

ファーストネーム セカンドネーム 番号

各連絡先は改行で区切られています。行数を数え、動的メモリ割り当てを使用して、行数と同じサイズの構造体の配列を作成することから始めました。

しかし、テキストファイルから情報を読み込んで画面に出力しようとすると、意味不明なものしか得られません。解決策を見つけるためにインターネットを調べてみましたが、見つけたものはすべて別の構文を使用しているようです。

これまでの私のコードは次のとおりです。

#include <iostream>
#include <fstream>
#include <istream>

char in[20];
char out[20];

using namespace std;

struct contact
{
    char firstName[14];
    char surName[14];
    char number[9];
};
//structure definition

int main(void){

    cout << "Please enter the input filename: " << endl;
    cin >> in;
    ifstream input(in);

    if(!input){
        cerr << "failed to open input file " << in << endl;
        exit(1);
    }

    cout << "Please enter tne output filename: " << endl;
    cin >> out;

    // read in the input and output filenames

    char a;
    int b=0;
    while (input.good ())
    {
        a=input.get ();
        if (a=='\n')
        {
            b++;
        }
    }
    // count the number of lines in the input file

    input.seekg (0, ios::beg);

    //rewind to beginning of file

    contact* list = new contact[b];

    //dynamically create memory space for array of contacts

    int i = 0.;
      while(input){
            if(i >= b) break;
            if(input >> *list[i].firstName >> *list[i].surName >> *list[i].number) i++;  
            else break;
      }
    input.close();

    //read information from input file into array of contacts

    for(int N = 0; N < b; N++){
        cout << list[N].firstName << list[N].surName << list[N].number << endl;
    }

    ofstream output(out);
    int k = 0;
    for(int k = 0; k<b; k++){
        output << list[k].firstName << "        " << list[k].surName << "       " << list[k].number << endl;
    }

    //print out the unsorted list to screen and write to output file
    //i've done both here just to check, won't print to screen in final version

    output.close();
    delete []list;

}       // end of main()
4

2 に答える 2

0

ファイルの場所を最初にリセットしましたが、最初に行数を読み取ったときから、ファイル eofbit はまだ true とラベル付けされています。これに対する簡単な解決策は、行を読んだ後にファイルを再度開くことです。これにより、行カウントがコードをクリーンアップする関数になる可能性があります。

int lines(const string path)
{
    ifstream tmp(path.c_str());
    string temp;
    int count = 0;
    getline(inFile,temp);
    while(inFile)
    {
       count++;
       getline(inFile,temp);
    }
    tmp.close();
    return count;
}
于 2012-12-11T01:44:30.050 に答える