File I/O help

C

cyberfire451

I'm fairly new to C++ and have a question.
I'm wodering if there is a way to only read a certain column within a
file. For example:
I have a file with this structured format, (it's just a text file)

David Politzer X A

to test a value I want to read in the X and not the rest. Any help
would be appreciated. Note this is for and entry level C++ class and
the help should be oriented to help me understand better.
 
A

Alf P. Steinbach

* cyberfire451:
I'm fairly new to C++ and have a question.
I'm wodering if there is a way to only read a certain column within a
file. For example:
I have a file with this structured format, (it's just a text file)

David Politzer X A

to test a value I want to read in the X and not the rest. Any help
would be appreciated. Note this is for and entry level C++ class and
the help should be oriented to help me understand better.


It much depends on the format.

If the data in each field always consists of a string with no blanks,
and X is always the third such string, use the ">>" operator,

For each line:
* f >> forename >> surname >> xValue >> aValue;

where forename, surname, xValue and aValue are std::string variables,
and f is a std::istream such as std::cin or a std::ifstream variable.

Otherwise,

For each line:

* Use std::getline to read the line into a std::string variable.

* Then, find the character position of the start of X, and of the
end of X. Perhaps these positions are always the same? Or perhaps
the fields are separeted e.g. by tabs, which means you need to
search through the string. The solution much depends on this.

* Then use std::string::substr to retrieve X from the line.

Hth.

- Alf
 

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

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,649
Latest member
MargaretCo

Latest Threads

Top