Reputation: 31
I apologize in advance if this has already been covered, but I've been looking for the past couple of hours and i'm being driven to the point of insanity.
I have to basically read in an input file that could have integers anywhere in the file.
sample input:
word word word word 5 word word 7 word word word word word 8 word word word word. word word word word word word 67. word 9
I need to get only the integers, then put said integers in a vector. I tried just reading it in a character at a time, then converting it to a type int, but that doesn't really work. I tried reading it in via string, then converting it to a integer, but that doesn't work either. The numbers could be in any place within the file. I hope this makes sense, but any help would be appreciated.
I am using Visual Studios if it matters. I'm also programming in c++.
Upvotes: 3
Views: 104
Reputation: 13320
You can also try <regex>
:
const std::string input{"word word word word 5 word word 7 word word word word word 8 word word word word. word word word word word word 67. word 9"};
std::regex numbers_pattern(R"((\b\d+()\b))");
for (std::sregex_token_iterator begin(input.begin(), input.end(),
numbers_pattern, 1), end; begin != end; ++begin)
{
std::cout << *begin << '\n';
}
With this regex iterator you can look for numbers in the string and capture them as text, then you transform the text into number with the approach you like the most.
Take a look to the Demo.
To use it with a file you should replace the std::string input
with a file stream.
Upvotes: 0
Reputation: 249133
This program looks for integers on stdin (you can use another istream if you like) and prints them, one per line.
#include <iostream>
int main()
{
std::istream& input = std::cin;
intmax_t value;
while (!input.eof()) {
if (input >> value) {
std::cout << value << '\n';
} else { // not an integer, ignore up to next space
input.clear();
input.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
}
}
}
Upvotes: 2