Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read input separated by whitespace(s) or newline...?

Tags:

I'm grabbing input from a standard input stream. Such as,

1 2 3 4 5 

or

1 2 3 4 5 

I'm using:

std::string in; std::getline(std::cin, in); 

But that just grabs upto the newline, correct? How can I get input whether they are separated by newline OR whitespace(s) using only iosteam, string, and cstdlib?

like image 550
user618712 Avatar asked Apr 21 '11 02:04

user618712


People also ask

How do you take user input separated by space in Python?

Use an input() function to accept the list elements from a user in the format of a string separated by space. Next, use a split() function to split an input string by space. The split() method splits a string into a list.


1 Answers

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)         ... } 
like image 85
Tony Delroy Avatar answered Sep 19 '22 13:09

Tony Delroy