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”分配给 Bob 和 Chris。如果有人能告诉我如何以某种方式指向文本文件的某些行,我将不胜感激,因此当我将它们添加到文本文件中时,将 Bob 分配到第 1 行,将 Chris 分配到第 2 行,并将更多客户分配到其他行。

4

2 回答 2

0

istream.getline() http://www.cplusplus.com/reference/iostream/istream/getline/可能是你的答案。一次只读一行。

这里有一个小例子: http ://www.cplusplus.com/forum/beginner/27799/

我的一个旧家庭作业中的一个小例子:

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 回答
0

你对 Bob 和 Chris 所做的一切都发生在构造函数中。因此,正如所写,您的代码说:当流处于良好状态并且它不是文件的结尾(关键点)时,请写入此处。

好吧,如果您考虑一下,这将一直读取到每个Customer. 那不是你想要的。我可能会建议将名称添加为每条记录的数据文件中的第一个字段。然后,您可以在文件中搜索正确的记录,假设您确保名称都是唯一定义的,然后逐个字符串地提取数据。这样它就不会每次都从头到尾阅读。我将“Bob”添加为第 1 行的第一个字段,将“Chris”添加到第 2 行并制作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
      }
  }

}

你这样做的方式会导致问题。唯一确定它起作用的方法是,如果您知道记录在文件中的位置。如果你有五张唱片呢?当你到达第三个时,你将不得不ignore或类似地,在你正在处理的那个之前的所有字段。此外,人类可以很方便地读取数据文件的打印件。为每条记录提供标签(名称)的另一个原因。另外,你显然是using namespace std;,所以我也这样做了,但它不受欢迎。

于 2012-08-09T02:33:11.330 回答