You are not that far off. replace_num_with_x()
is creating a stringstream
that is not being using anywhere. Change the loop to read individual words from that stream, eg:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string replace_num_with_x(const string &str);
int main() {
cout << "Please enter a line of text:";
string str;
getline(cin, str);
cout << replace_num_with_x(str);
}
string replace_num_with_x(const string &str) {
istringstream str_strm(str);
string word, result;
while (str_strm >> word) {
bool all_digits = true;
string::size_type word_size = word.size();
for (string::size_type i = 0; i < word_size; ++i) {
if (word[i] < '0' || word[i] > '9') {
all_digits = false;
break;
}
}
if (!result.empty()) {
result += ' ';
}
if (all_digits) {
result.append(word_size, 'x');
} else {
result += word;
}
}
return result;
}
Demo
Alternatively:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
string replace_num_with_x(const string &str);
int main() {
cout << "Please enter a line of text:";
string str;
getline(cin, str);
cout << replace_num_with_x(str);
}
string replace_num_with_x(const string &str) {
istringstream str_strm(str);
ostringstream out_strm;
string word;
if (str_strm >> word) {
do {
if (word.find_first_not_of("0123456789") == string::npos) {
fill(word.begin(), word.end(), 'x');
}
out_strm << word;
if (!(str_strm >> word)) break;
out_strm << ' ';
}
while (true);
}
return out_strm.str();
}
Demo
UPDATE: if you are not allowed to use istringstream
, then you can do something more like this instead:
#include <iostream>
#include <string>
using namespace std;
string replace_num_with_x(const string &str);
int main() {
cout << "Please enter a line of text:";
string str;
getline(cin, str);
cout << replace_num_with_x(str);
}
string replace_num_with_x(const string &str) {
string word, result;
string::size_type str_size = str.size(), start = 0, end;
do {
end = str.find(' ', start);
if (end == string::npos) {
word = str.substr(start);
start = str_size;
}
else {
word = str.substr(start, end - start);
start = end + 1;
}
bool all_digits = true;
string::size_type word_size = word.size();
for (string::size_type i = 0; i < word_size; ++i) {
if (word[i] < '0' || word[i] > '9') {
all_digits = false;
break;
}
}
if (!result.empty()) {
result += ' ';
}
if (all_digits) {
result.append(word_size, 'x');
} else {
result += word;
}
}
while (start < str_size);
return result;
}
Demo