从文件中读取行并存储在单独的字符串变量中

时间:2013-04-23 01:33:57

标签: c++ variable-assignment fstream getline

我正在为作业创建一个银行终端。它能够为每个客户端添加包含名称,地址,社交#,雇主和收入的5个不同变量的客户。这些变量一旦填满并退出终端就会被写入文件。

我遇到的问题是在启动终端时我需要从文件中读取这些值,每个值都在各自的行中,并将它们存储在各自的变量中,以便在addClient()函数中使用。这是使事情比提交整个项目更容易的代码片段:

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

using namespace std;

int main()
{
  using namespace std;

  std::ifstream infile2("client-info.txt");

  //Strings used for respective items from file
  string clientName, clientAddress, clientSocial, clientEmployer, clientIncome;

  //Here is where I am having the problem of reading the info from the file
  //line by line and storing it in respective variables.
  while (infile2)
  {
     getline(infile2,clientName);
     getline(infile2,clientAddress);
     getline(infile2,clientSocial);
     getline(infile2,clientEmployer);
     getline(infile2,clientIncome);

     client.addClient(clientName, clientAddress, clientSocial, clientEmployer, clientIncome);
  }
  infile2.close();
}

例如,文件存储为。

John Doe
123 Easy Lane
123-45-6789
USSRC
36000

我遇到的问题是我无法找到一条可靠的方法来获取每一行并将它们存储在各自的字符串中。对于作业,我不必处理空白等。因此,0-4行将用于一个客户端,5-9用于另一个客户端等等。

非常感谢正确推动,谢谢!

2 个答案:

答案 0 :(得分:3)

如果addClient函数接受了5个参数,那么您当前的主函数已经解决了您的问题。

如果您想将这5个字符串放入单个字符串中,请在addClient函数内处理此单个字符串。

您可以创建一个类:

class ClientInfo
{
 private:
   string clientName;
   string clientAddress; 
   string clientSocial;
   string clientEmployer,;
   string clientIncome;
public:
  ClientInfo(string name, string addr, string ssn, 
                 string employer, string income):
                  clientName(name), clientAddress(addr), clientSocial(ssn),
                  clientEmployer(employer), clientIncome(income)
  {
  }
};

然后在main内,您可以执行以下操作:

ClientInfo currentClient(clientName, clientAddress, 
                clientSocial, clientEmployer, clientIncome);
client.addClient(currentClient);

答案 1 :(得分:0)

我认为你遇到的唯一问题是当你调用getline时,你没有传递参数。在这种情况下,我认为您需要使用换行符分隔符。

  while (infile2)

      {
         getline(infile2,clientName, '\n');
         getline(infile2,clientAddress, '\n');
         getline(infile2,clientSocial, '\n');
         getline(infile2,clientEmployer, '\n');
         getline(infile2,clientIncome, '\n');

         client.addClient(clientName, clientAddress, clientSocial, clientEmployer, clientIncome);
      }

我不确定'\ n'语法,但这会读取文件,直到它到达换行符然后转到下一行。