I want to read the integers from a file with numbers and letters. For example the file is file.txt:
kdgfg8aa
907dffd99ss
kaasjelgg65
9h6hb0v32
Then I want to display which of the numbers are odd or even.
So, I want my output:
8 is an even number
907 is an odd number.
99 is an odd number.
65 is an odd number.
9 is an odd number.
6 is an even number.
0 is an even number.
32 is an even number.
Is it possible to do this without using strings or vectors?
I guess it depends how big a number you are prepared to tolerate. @dutch's solution (below) will certainly be much faster if the number fits in an int.
#include <iostream>
#include <cctype>
#include <fstream>
int main()
{
constchar* state[] = {"even", "odd"};
std::ifstream fin("filename.txt");
if (!fin.is_open())
return (std::cout << "Cannot open input file\n"), 1;
for (int ch, num; (ch = fin.peek()) != EOF; )
if (std::isdigit(ch)) {
fin >> num;
std::cout << num << " is an " << state[num % 2] << " number.\n";
} else
fin.ignore();
}
8 is an even number.
907 is an odd number.
99 is an odd number.
65 is an odd number.
9 is an odd number.
6 is an even number.
0 is an even number.
32 is an even number.
Note that unget() is not guaranteed to succeed and if used the stream state should be checked. unget() uses sungetc() for the underlying stream buffer which fails if a putback position is not available.