'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.
Solution 1:[1]
Regardless of the language, this will typically consist of the following steps:
- Open the file
- Read (formatted) the first two integers
- Close the file
In C++, we can use ifstream
- To open:
std::ifstream fil;
fil.open("in.txt");
- To read:
int x, y;
fil >> x >> y;
- To close:
fil.close();
Make sure to include the fstream header:
#include <fstream>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jdabtieu |
