You'll want to validate the input one way or another and ignore it or not depending on whether it's a number. The easiest way to do this is to test a call to cin's >> operator.
Code:
#include <iostream>
using namespace std;
int main()
{
int x;
while (cin>> x)
cout<< x <<endl;
}
However, if you want to keep taking input after the non-number then you need to do a little more work. The most common method is to read everything as a line, then parse it.
Code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string line;
int x;
while (getline(cin, line)) {
istringstream in(line);
if (in>> x)
cout<< x <<endl;
}
}
Again, there's a problem. What if you want to allow for more than one number in a line, and you still want to ignore any invalid numbers? Once again, it's harder:
Code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
class Split {
public:
typedef std::vector<std::string>::iterator iterator;
typedef std::vector<std::string>::const_iterator const_iterator;
public:
Split(const std::string& s, const char sep);
public:
iterator begin() { return split.begin(); }
const_iterator begin() const { return split.begin(); }
iterator end() { return split.end(); }
const_iterator end() const { return split.end(); }
private:
std::string original;
std::vector<std::string> split;
};
Split::Split(const std::string& s, const char sep)
: original(s)
{
std::istringstream in(original);
std::string token;
while (getline(in, token, sep))
split.push_back(token);
}
using namespace std;
int main()
{
string line;
int x;
while (getline(cin, line)) {
Split t(line, ' ');
for (Split::const_iterator it = t.begin();
it != t.end(); ++it)
{
istringstream in(*it);
if (in>> x)
cout<< x <<endl;
}
}
}
Fortunately, if you do it carefully then you can reuse the code for splitting up a line.