How to change delineator in iostream?

  • Thread starter Jennica Humphrey
  • Start date
J

Jennica Humphrey

Let's say I have something like this:

ifstream inFile( buffer, ios::in );

while ( inFile >> name >> value ) { // read lines
cout << "Name: " << name << " Value: " << value;
}

The file reads one word at a time, which appears to be delineated by
whitespace or a newline. How do I change the delineator, for example,
using '=' instead of ' '?
 
J

Jon Bell

while ( inFile >> name >> value ) { // read lines
cout << "Name: " << name << " Value: " << value;
}

The file reads one word at a time, which appears to be delineated by
whitespace or a newline. How do I change the delineator, for example,
using '=' instead of ' '?

Use getline() instead of the >> operator. It allows you to specify a
terminator character in place of the default '\n'. For example, if you
have three tab-delimited fields per line (and each line is terminated by a
newline):

std::string field1, field2, field3;
while (getline (infile, field1, '\t') && getline (inFile, field2, '\t')
&& getline (inFile, field3))
{
cout << field1 << '\t' << field2 << '\t' << field3 << endl;
}
 
J

Jason Leasure

Jennica said:
Let's say I have something like this:

ifstream inFile( buffer, ios::in );

while ( inFile >> name >> value ) { // read lines
cout << "Name: " << name << " Value: " << value;
}

The file reads one word at a time, which appears to be delineated by
whitespace or a newline. How do I change the delineator, for example,
using '=' instead of ' '?


A co-worker asked me this the other day, as it's apparently really easy
to do in Java..

I can't tell you exactly how, but I think you can do this by
constructing a locale with a ctype for which isspace returns true on '='
(and false on ' ', '\t', etc..) Then "imbue" whatever stream you want
to get input from with your new locale..

You could build a nice little stream manipulator which does this all for
you.



Jason
 
J

Jennica Humphrey

Thank you I did:

while ( inFile.getline( name, 40, '=' ) && inFile.getline( value, 50 ) )

and that did the trick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,160
Messages
2,570,890
Members
47,423
Latest member
henerygril

Latest Threads

Top