Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading a tab character

Status
Not open for further replies.

trent101

Programmer
Nov 4, 2005
50
AU
Hey,

I am creating a simple win32 consol program using vc++.net.

My job is to read in data from two tab-delimeted files, one is a text file and the other has no extension so I am assuming is binary?

I would like to know how to find out when I read in the tab delimerter, so I know when a field is finished.

I can read id data using:

myfile >> field1 >> field 2 >> feild3; ...etc.

However this reads in each word and counts spaces as a new word.

How can I tell when I have reached the tab character, so I know that the data before it is a field?


Thanks for your time
 
It is far easier if you use C I/O instead of C++ I/O.

1) fgets the whole line
2) examine the line for tab characters (\t or \011 or \x09)
3) alternatively break it up using strtok

It may be old fashioned and not be the latest technology but it is simple and it will work.
 
What about something like this:
Code:
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

struct Record
{
	string	name;
	string	address;
	string	phone;
};

int main()
{
	ifstream inFile( "c:/temp/filename.txt" );

	if ( !inFile )
	{
		cout << "Error opening file!";
		return 1;
	}

	vector<string> lines;
	string line;

	// Read each line into a vector.
	while ( getline( inFile, line ) )
	{
		lines.push_back( line );
	}

	vector<Record> records;
	string field;

	// Parse each line and put the fields into a vector of records.
	for ( vector<string>::iterator it = lines.begin(); it != lines.end(); ++it )
	{
		Record record;
		size_t start = 0;
		size_t end   = it->find( "\t" );

		record.name = it->substr( start, end );
		start = end + 1;

		end = it->find( "\t", start );
		record.address = it->substr( start, (end - start) );
		start = end + 1;

		record.phone = it->substr( start );
		records.push_back( record );
	}

	for ( vector<Record>::iterator it = records.begin(); it != records.end(); ++it )
	{
		cout << it->name    << endl
			 << it->address << endl
			 << it->phone   << endl
			 << "--------------------------------------" << endl;
	}

	return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top