In: Computer Science
(Please write in C++) Write a program that reads in a line consisting of a student’s name, Social Security number, user ID, and password. The program outputs the string in which all the digits of the Social Security number and all the characters in the password are replaced by x. (The Social Security number is in the form 000-00-0000, and the user ID and the password do not contain any spaces.) Your program should not use the operator [ ] to access a string element. Use the appropriate functions described in Table 7-1 below.
Expression | ||
---|---|---|
strVar.at(index) | ||
strVar[index] | ||
strVar.append(n, ch) | ||
strVar.append(str) | ||
strVar.clear() | ||
strVar.compare(str) | ||
strVar.empty() | ||
strVar.erase() | ||
strVar.erase(pos, n) | ||
strVar.find(str) | ||
strVar.find(str, pos) | ||
strVar.find_first_of(str, pos) | ||
strVar.find_first_not_of(str, pos) | ||
strVar.insert(pos, n, ch) | ||
strVar.insert(pos, str) | ||
strVar.length() | ||
strVar.replace(pos, n, str) | ||
strVar.substr(pos, len) | ||
strVar.size() | ||
strVar.swap(str1) |
With an input of: John Doe 333224444 DoeJ 123Password
The results should be: John Doe xxxxxxxxx DoeJ xxxxxxxxxxx
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
#include <iostream>
#include<string>
using namespace std;
int main() {
string data;
cout<<"Enter input: ";
getline(cin,data);
cout<<data<<endl;
int ssn_start_index=0;
int ssn_end_index=0;
int pass_start_index=0;
int pass_end_index=data.size()-1;
int space_count=0;
// loop through the string
for(int i=0;i<data.size();i++)
{
// is the character a space?
if(data.at(i)==' ')
{
// increase the count
space_count++;
// ssn starts from next character
if(space_count==2)
{
ssn_start_index=i+1;
}
// ssn ends here
if(space_count==3)
{
ssn_end_index=i-1;
}
// password starts from next character
if(space_count==4)
{
pass_start_index=i+1;
}
}
}
// Now , we know the index for start and end for both
password and SSN number
// replace them with *
for(int
pos=ssn_start_index;pos<=ssn_end_index;pos++)
data.replace(pos,1,"*");
for(int
pos=pass_start_index;pos<=pass_end_index;pos++)
data.replace(pos,1,"*");
cout<<data;
return 0;
}
===========