Just use:
your_type x;
while (std::cin >> x)
{
// use x
}
operator>>
will skip whitespace by default. You can chain things to read several variables at once:
if (std::cin >> my_string >> my_number)
// use them both
getline()
reads everything on a single line, returning that whether it's empty or contains dozens of space-separated elements. If you provide the optional alternative delimiter ala getline(std::cin, my_string, ' ')
it still won't do what you seem to want, e.g. tabs will be read into my_string
.
Probably not needed for this, but a fairly common requirement that you may be interested in sometime soon is to read a single newline-delimited line, then split it into components...
std::string line;
while (std::getline(std::cin, line))
{
std::istringstream iss(line);
first_type first_on_line;
second_type second_on_line;
third_type third_on_line;
if (iss >> first_on_line >> second_on_line >> third_on_line)
...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…