There are a couple of ways to do this. One of them involves reading the input right off of the input stream, and another involves dumping the whole input into a string and picking out the parts that you want.
Since the name is followed immediately by the SSN, one thing you could do is grab input and stick it onto the name until you run into a digit.
Then do what I mentioned above.
For instance, something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <string>
#include <cctype>
using std::cout;
using std::cin;
using std::string;
using std::isdigit;
int main()
{
cout << "Enter your name followed by a something starting with a number:";
cout << "\n>> ";
string name;
while (!isdigit(cin.peek())) // Peek at the next character in the input
{
string tmp;
cin >> tmp;
cin.ignore(); // Get rid of the whitespace
name += (tmp + ' ');
}
name.pop_back(); // Get rid of the trailing space, not like it matters
// If you have an older compiler, you might need to replace that line with
// name.erase(name.end()-1);
string other;
cin >> other;
cout << "Your name is " << name;
cout << "\nand the other thing you entered was " << other;
}
|
This produces the output:
Enter your name followed by a something starting with a number:
>> Jay Jay the Jet Plane 123that's-me!
Your name is Jay Jay the Jet Plane
and the other thing you entered was 123that's-me! |
If you decide to use
getline to grab the whole input all at once, you can use
std::find_if (
http://www.cplusplus.com/reference/algorithm/find_if/ ) to find where the first digit (presumably the start of the SSN) is, and then use the
substr member function of
std::string to grab everything up to that point (which will presumably be the full name).
As for "actually" replacing the digits of the SSN, you can use
std::replace_if (
http://www.cplusplus.com/reference/algorithm/replace_if/ ) to replace all of the digits with 'x's.
(Or you can just do what you've already been doing, since you know that the SSN has to be in that format)
(For those of you who can tell, I'm just trying to dodge the use of
operator[]
here.)
Or...since you can't use
operator[]
to access string elements, you can just use iterators for everything instead:
1 2 3 4 5
|
for (std::string::iterator it = ssn.begin(); it != ssn.end(); ++it)
{
if (std::isdigit(*it)) // or if (*it != '-')
*it = 'x'; // Replace digits with 'x'
}
|
(Geez, why didn't I think of that before?)