Mellester Mellester - 11 months ago 99
C++ Question

c++ removing whitespace fails by using iterators

This codes compiles and works as intended but the comment line doesnt for some reason can anybody tell me why.

#include <iostream>

int main()
std::cout << "Enter a line:\n";
std::string Line;
const std::string Whitespace = " \t\t\f\v\n\r";
//std::string Line= std::string(Line.find_first_not_of(Whitespace),Line.find_last_not_of(Whitespace)+1); // Why doesnt this work?
std::string Line= Line.substr(Line.find_first_not_of(Whitespace),Line.find_last_not_of(Whitespace)+1);
std::cout << "You entered:" << Line << "\n";

Edit I was under the impression find las returns a iterator not a size_t so that is why I was confused

Answer Source

Not only the commented line, but another will also fail if there is space in the begin of string.

First line fail (to compile) because string::find_first_not_of return size_t. And construct string from two size just make no sense.

Second line may fail because string::substr accept length (not end) as it's second parameter.