Basically I need to read from a text file that looks like this

customer Kevin
checking myaccount 100.00
bond mybond1 1997 100 0.07
bond mybond2 2010 200 0.01
irabond myirabond1 1997 100 0.06
end
customer Mark
irabond hisirabond1 1999 200 0.08
bond hisbond1 1990 2000 0.10
end

I need to get each customers info, name, account names and balance, etc into an object. This I know how to do. What I don't know how to do is break up the text file to allow this.

Here's what I have so far:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;

int main()
{
	ifstream in_file;
	string file_name;
	string temp;
	string allText;
	cout<<"Please enter the file name: ";
	cin>>file_name;

	bool loop = true;

	//stringstream ss;

	in_file.open(file_name);

	while(in_file>>temp)
	{
		stringstream ss;
		ss << temp;
		while(loop)
		{
			string st;
			ss >> st;
			if (st =="end")
			{
			
				loop = false;
				
			}
			if (st == ""){loop = false;}
			allText += st;
		}
		loop = true;
	}

	system ("pause");
}

I can get a string of words until the word "end", which is what I want, but I'm confused as to where to go next. How to I get the cusomter name? I guess I could look for customer in the string and say, delete customer, but store the next word into this vector. Then look for the word checking, delete it and store the name, etc into this vector and so on.

Would this work? How would I go about doing it?

Recommended Answers

All 2 Replies

I can get a string of words until the word "end", which is what I want, but I'm confused as to where to go next. How to I get the cusomter name?

Where is the customer name? Did you read it? Is it somewhere else?

To read a line of text, use std::getline() http://www.cplusplus.com/reference/string/getline/

To do something with every non blank line in the text file:

std::string line ;
while( std::getline( in_file, line ) && !line.empty() )
{
   // do something with line
}

To parse a line that has been read, use a std::istringstream. For example:

std::string line ;
while( std::getline( in_file, line ) && line != "end" )
{
   std::istringstream stm(line) ;
   std::string ac_name ;
   int year ;
   double balance ;
   double rate ;
   if( stm >> ac_name >> year >> balance >> rate )
   {
       // do something with them
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.