You'd need a bit more than just one line
variable: as is your code won't terminate if the string contains a non-space character. Of course, this assumes that it compiles in the first place as there are a number of parenthesis and a semicolon missing (also, your question doesn't match your code: there is no function substring
; if you want to program effectively, you have to be very precise about everything: computer take your statements very literal). You probably want to chop your line
up into its bits and put them into some sort of container.
Once over these trivial aspect, you might want to consider using ' '
instead of " "
because in this case the compiler and library can assume that you want to look for just one character rather than for a sequence of characters. This can be quite a bit faster. However, this is actually not whitespace but just space. Whitespace also includes a number of special characters like '\t'
(tab), '\r'
(carriage return), '\n'
(newline), '\v'
(vertical tab), '\b'
(backspace), and '\f'
(form feed). Speaking of speed you probably don't want to erase()
bits from the beginning of the string as this yield an O(n * n) algorithm while this can be done O(n) e.g. by keeping a variable with the position. This also avoid the problem of searching twice which is unnecessary expensive. You should also consider the behavior if there are two adjacent strings: should this produce an empty string in your sequence or should this be treated as if there were one space (in which case you might want to also use first_not_of()
).
Actually, I just reread the problem statement: if you just want to extract the string up to the first space, you don't need erase()
, empty()
, or a loop if you insist on using assign()
. However, this can be done using even two std::string
members: find()
and erase()
:
line.erase(line.find(" \t\r\n\v\b\f"));