Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract the numbers in a file in C++?

I have some similar files like this:
15 12
0 0 168
0 2 92
(more numbers)…

I want to extract the first two (in this case: 15 and 12) into integers, how can I accomplish that?
By the way, the first two numbers sometime will be unit digits sometimes will be hundreds digits.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Regardless of the language, this will typically consist of the following steps:

  1. Open the file
  2. Read (formatted) the first two integers
  3. Close the file

In C++, we can use ifstream

  1. To open:
std::ifstream fil;
fil.open("in.txt");
  1. To read:
int x, y;
fil >> x >> y;
  1. To close:
fil.close();

Make sure to include the fstream header:

#include <fstream>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading