You read a string (line 20).
You convert that into a string with no white spaces via noWhiteSpace( line ), as on line 21.
Here, I chose to print it straight out - but you could just reassign it to line as line = noWhiteSpace( line );
Maybe, you could also use the stream-iterator approach and copy into a string rather than straight to cout. By default it ignores the white spaces.
Sorry, @SOURABH PRAKASH PATI, I would have to stick to the noWhiteSpace() function.
The nearest that I can get to with stream iterators is the following. However, it DOESN'T WORK as there is nothing to conclude the cin stream (until you hit CTRL-C).
Can anyone else in the forum advise?
NON-WORKING PROGRAM
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
#include<string>
#include<iterator>
#include<algorithm>
usingnamespace std;
int main()
{
string line;
cout << "Input some text: ";
copy( istream_iterator<char>( cin ), {}, back_inserter( line ) ); // doesn't work properly (requires you to hit CTRL-C)
cout << "You have just input: " << line << '\n';
}
EDIT:
Well, I did eventually come up with this contrived piece of garbage, but it will unequivocally go down as "Palooka code", so don't use it! I think my original noWhiteSpace() routine was far more sensible.
#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>
// function to return a copy of a string without whitespace
std::string removeWhiteSpace(std::string input) {
// since we're "removing" things, why not use std::remove_if?
// EDIT: also make sure to honour the preconditions of std::isspace
auto new_end = std::remove_if(std::begin(input), std::end(input),
[](unsignedchar c) { return std::isspace(c); });
// make sure to resize the string - remove_if doesn't actually modify it!
input.erase(new_end, std::end(input));
return input;
}
// wrap our desired usage in a function
std::string getLineNoSpaces() {
std::string line;
std::getline(std::cin, line);
return removeWhiteSpace(line);
}
int main() {
std::cout << "Input some text: ";
std::string line = getLineNoSpaces();
std::cout << "You have just input: " << line << "\n";
return 0;
}