Reputation: 577
1 = 0 0 97 218
2 = 588 0 97 218
3 = 196 438 97 218
4 = 0 657 97 218
5 = 294 438 97 218
I have txt file like above.How can i read only integers from this file without = ?
Upvotes: 0
Views: 296
Reputation: 490048
Another possibility would be a facet that classifies =
as white space:
class my_ctype : public std::ctype<char>
{
mask my_table[table_size];
public:
my_ctype(size_t refs = 0)
: std::ctype<char>(&my_table[0], false, refs)
{
std::copy_n(classic_table(), table_size, my_table);
my_table['='] = (mask)space;
}
};
Then imbue your stream with a locale including this facet, then read the numbers as if the =
wasn't there at all:
int main() {
std::istringstream input(
"1 = 0 0 97 218\n"
"2 = 588 0 97 218\n"
"3 = 196 438 97 218\n"
"4 = 0 657 97 218\n"
"5 = 294 438 97 218\n"
);
std::locale x(std::locale::classic(), new my_ctype);
input.imbue(x);
std::vector<int> numbers((std::istream_iterator<int>(input)),
std::istream_iterator<int>());
std::cout << "the numbers add up to: "
<< std::accumulate(numbers.begin(), numbers.end(), 0)
<< "\n";
return 0;
}
Granted, it's probably not very sensible to add up all the numbers, since the first one on each line seems to be a line number -- that's just a quick demo to show that we're really reading the numbers without the extra "stuff" causing any problems.
Upvotes: 1
Reputation: 476950
Here's the basic framework: read line-by-line and parse.
for (std::string line; std::getline(std::cin, line); )
{
std::istringstream iss(line);
int n;
char c;
if (!(iss >> n >> c) || c != '=')
{
// parsing error, skipping line
continue;
}
for (int i; iss >> i; )
{
std::cout << n << " = " << i << std::endl; // or whatever;
}
}
To read a file via std::cin
, pipe it into your program, like ./myprog < thefile.txt
.
Upvotes: 0