So, I am working on a program that replaces every digit entered into cin with an x but if it's something like john17 then don't (so basically, if the word is an integer, replace the digits, else, keep the word as-is). I am struggling to find a solution here. How do I break up the words in the line entered and test whether it's an integer?
So to add some clarification...it's a line of text like: "My userID is john17 and my 4 digit pin is 1234 which is secret", so I want to keep john17 there but replace 4 with x and 1234 with all x's
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Our variables
string str;
string result;
//Function Prototypes
void replace_num_with_x(string str);
int main() {
cout<<"Please enter a line of text:";
getline(cin, str);
replace_num_with_x(str);
cout<<result;
}
//Function Definition
void replace_num_with_x(string str) {
stringstream str_strm;
str_strm << str; //Convert string to stringstream
for(int i = 0; i <= str.length() ; i++) {
if((char)str[i] >=48 && (char)str[i] <= 57) {
result +='x';
}
else {
result +=str[i];
}
}
}
Aucun commentaire:
Enregistrer un commentaire