Howto loop this function?

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
30
31
32
33
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>

using namespace std;

//BEGIN FUNCTION PROTOTYPE
    void redactDigits( string & s );
//Start Main
int main ()
{
string s;
redactDigits(s) ;

}
   void redactDigits( string & s ){
 {
    cout<<"Input you information: ";
    cin>>s;
    replace(s.begin(),s.end(),'4','*');
    replace(s.begin(),s.end(),'3','*');
    replace(s.begin(),s.end(),'2','*');
    replace(s.begin(),s.end(),'1','*');
    replace(s.begin(),s.end(),'5','*');
    replace(s.begin(),s.end(),'6','*');
    replace(s.begin(),s.end(),'7','*');
    replace(s.begin(),s.end(),'8','*');
    replace(s.begin(),s.end(),'9','*');
    replace(s.begin(),s.end(),'0','*');
    cout<<s<<endl;
}
    }

I need to replace every number in my input with the symbol '*'. I don't know how to do it with a loop. For example my input is: "HelloTheir453Their54Hello" and outputs to "HelloTheir***Their**Hello". Instead of having all of those replace functions can I make one loop? How? Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <algorithm>
#include <ctype.h> // for http://www.cplusplus.com/reference/cctype/isdigit/

int main()
{
    std::string str = "HelloTheir453Their54Hello" ;

    // loop
    for( char& c : str ) if( ::isdigit(c) ) c = '*' ;
    std::cout << str << '\n' ;

    str = "cvvc2hvc7r6464677VJVJvju78uR&R56fuvfcJv" ;

    // algorithm http://www.cplusplus.com/reference/algorithm/replace_if/
    std::replace_if( str.begin(), str.end(), ::isdigit, '*' ) ;
    std::cout << str << '\n' ;
}

http://ideone.com/uXVdUY
Last edited on
You could make that easier using an iterator. More easier, using C++11's ranged-based for system.
eg:
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
/********************************************************************
aim:
-
********************************************************************/
//headers
#include <iostream>
#include <typeinfo>

//namespaces
using namespace std;
//other definitions and declarations


//main function
int main()
{
    string str;

    cout<<"Enter anything: ";
    getline(cin,str);
    for(auto& x:str)
        if(x=='1'||x=='2'||x=='3'||x=='4'||x=='5'||x=='6'||x=='7'||x=='8'||x=='9'||x=='0')
            x='*';
    cout<<"\nNew text: "<<str<<endl;
    cin.get();
    return 0;
}


Aceix.
Topic archived. No new replies allowed.