std::cin is an std::istream object associated with standard input. In the std::istream class (or, more probably, one of it's parent classes) operator >> is overloaded. It extracts a single block of characters which can either be all up to the first space, tab or newline or everything in the buffer if there's nothing there. Also,
operator>>()
will leave the last space, tab or newline in the buffer and only extract what's before it (which is why your program may skip inputs - it sees the whitespace and takes that to mean end-of-line ("EOF")). To counter this you can use
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
which will remove everything left in the buffer up to (and (probably) including) the last newline (or whatever you put instead of the '\n').
std::getline() puts all whitespace (including the newline) into the string you supply, so you don't have to do the
std::cin.ignore()
thing.
I prefer to use std::getline(). For dealing with integers you should use a stringstream, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::stringstream sstrm;
std::string str;
int i;
std::cout << "Enter a number: " << std::flush;
std::getline(std::cin, str);
sstrm << str;
sstrm >> i;
return 0;
}
|
And yes, you can use it without the
std::
suffix if you put
using namespace std;
. However I personally don't advise this for several reasons.