0

これが私のメインの一部です:

int main() {
  Inventory Master;
  bool flag;

  Customer Bob("Bob", "CreditCard.txt");
  Customer Chris("Chris", "CreditCard.txt" ); 
}

これが私の方法です:

Customer::Customer( string n, string fileName ) {
  name = n;
  ifstream Credit;

  Credit.open(fileName.c_str(), ios::in);

  while( Credit.good() && !Credit.eof() ) {
    Credit >> card >> balance >> ws;
    cout << card <<"\t" << balance << endl;

  }


 CreditCard _CC( int card, double balance);
}

これが私の「CreditCard.txtファイルです。

12345  15.00
32564  20.00

情報を表示する方法は、行 1「12345 15.00」を Bob に割り当て、行 2 を Chris に割り当て、顧客の新しいインスタンスまたはオブジェクトを作成する場合などに行います。しかし、私が現在実装している方法は、ボブとクリスの両方に「12345 15.00 と 32564 20.00」を割り当て続けることです。誰かがテキスト ファイルの特定の行をポイントする方法を教えていただければ、テキスト ファイルに追加したときに、ボブが 1 行目に、クリスが 2 行目に、さらに多くの顧客が他の行に割り当てられるようにする方法を教えていただければ助かります。

4

2 に答える 2

0

Bob と Chris に対して行っていることはすべて、コンストラクター内で行われます。したがって、書かれているように、コードは次のように述べています。

考えてみれば、これは のインスタンスごとにファイルの最後に到達するまで読み取りますCustomer。それはあなたが望むものではありません。各レコードのデータ ファイルの最初のフィールドとして名前を追加することをお勧めします。名前がすべて一意に定義されていることを確認してから、文字列ごとにデータを引き出すと仮定して、正しいレコードをファイルで検索できます。そうすれば、毎回最初から最後まで読むことはありません。1 行目の最初のフィールドに「Bob」を追加し、2 行目に「Chris」を追加して作成しましたstring name = "Chris";。そう...

#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
  string tempStr;
  string name = "Chris";
  ifstream Credit;

  Credit.open("Info.txt", ios::in);

  while( Credit.good() && !Credit.eof() ) 
  {
      getline(Credit, tempStr, ' ');//Reads the first records name field
      cout << tempStr << endl;
      if(name.compare(tempStr) == 0)//Compares the "name" to the field.
      {                            //If true they are the same
          //Proceed to do reading and assignments with additional getline statements
          cout << "Chris was matched the second time around!";
          Credit.setstate(ios::eofbit, true);//***Sets eof to true
      }
      else 
      {
          Credit.ignore(50, '\n');
          //That should put Credit in the proper position to read the next name
      }
  }

}

やり方次第で問題が発生します。確実に機能する唯一の方法は、レコードがファイル内のどこにあるかを知っている場合です。レコードが 5 つある場合はどうなりますか? 3 番目ignoreのフィールドに到達するまでに、作業中のフィールドより前のすべてのフィールドを 、または同様に処理する必要があります。また、人間がデータ ファイルの出力を読み取ることも便利です。各レコードにラベル (名前) を付けるもう 1 つの理由。また、あなたはどうやらusing namespace std;、私もそうでしたが、それは眉をひそめています。

于 2012-08-09T02:33:11.330 に答える
0

istream.getline() http://www.cplusplus.com/reference/iostream/istream/getline/があなたの答えかもしれません。一度に 1 行ずつ読むだけです。

ここに小さな例があります: http://www.cplusplus.com/forum/beginner/27799/

私の古い宿題の1つからの小さな例:

ifstream fin(fileName);
char buffer[256];

int count = 0;

if (fin.is_open())
{
    while (!fin.eof())
    {
        fin.getline(buffer, 256);
    }
}
于 2012-08-08T22:48:52.343 に答える