How can I remove all spaces between tokens in the following code?
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s[3] = {"a 1", "b 2", "c 3"};
for (int i = 0; i < 3; i++) {
stringstream ss(s[i]);
string tok;
while(getline(ss, tok, ' ')) // <-- need to fix
{
cout << tok << "."; // <-- need to fix
}
cout << endl;
}
return 0;
}
The expected output is
a.1
b.2
c.3
But the code generates
a.1.
b....2.
c..3.
>Solution :
You could use formatted input from the stream instead of std::getline. Formatted input skips whitespaces by default:
#include <iostream>
#include <sstream>
int main() {
std::string s[3] = {"a 1", "b 2", "c 3"};
for (const auto& str : s) {
std::istringstream ss(str);
if (std::string tok; ss >> tok) {
// at least one token read, print it
std::cout << tok;
// then read the rest and prepend them with '.' instead:
while (ss >> tok) {
std::cout << '.' << tok;
}
}
std::cout << '\n';
}
}
Output:
a.1
b.2
c.3