0

I am new to programming and I have this question. I have this file that I am opening

ifstream fin;
FILE * pFile;
pFile = fopen (fname,"r");

The file has 3 data each line. The first is an integer, the second is an alphabet and the third is an address(like computer memory address). How do I extract these line by line into 3 variables that I can process, and then repeat it with next line and so.

  • 1
    Have you tried anything yourselves to achieve this? Please see [this](http://mattgemmell.com/2008/12/08/what-have-you-tried/) and [this](http://meta.stackexchange.com/a/182380). Finally also, see [this](http://stackoverflow.com/questions/3946558/c-read-from-text-file-and-separate-into-variable) question on SO which is practically identical to your question. – crayzeewulf Nov 06 '13 at 00:26
  • First google result on "C++ open file" search: http://www.cplusplus.com/doc/tutorial/files/ After reading, you can split strings: http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – Nick Louloudakis Nov 06 '13 at 00:29

1 Answers1

0

You should know that there are preferred C++ methods for manipulation of files over C stdio methods:

  • Using standard predefined streams: std::ofstream for output and std::ifstream for input.
  • Formatted/Unformatted I/O such as operator<<(), operator>>(), read() and write().
  • In-memory I/O for manipulation of extracted data.

What you need for this particular case is input stream functionality along with formatted input. The formatted input will be done through operator>>().

But before you get to that, you have to instantiate a file stream. Since you're using input, std::ifstream will be used:

std::ifstream in("your/path.txt");

The next thing to do is to create the three variables whose values you will extract into the stream. Since you know the types beforehand, the types you will need is an integer, character, and string respectively:

int  num;
char letter;
std::string address;

The next thing to do is to use operator>>() to obtain the first valid value from the stream. The way it works is that the function analyses the type of the righthand operand and determines if the characters extracted from the file stream will create a valid value after parsing. When the stream hits whitespace, the new line character or the EOF (end-of-file) character (or a character that doesn't match that of the operand's type), extraction will stop.

What makes IOStreams powerful is that it allows chaining of expressions. So you are able to do this:

in >> num >> letter >> address;

which is equivalent to:

in >> num;
in >> letter;
in >> address;

This is all that is needed for this simple case. In more complex situations, loops and in-memory I/O might be needed for successful extractions.

David G
  • 94,763
  • 41
  • 167
  • 253