Possible to dynamically separate input?

Hi,

Is there a way to dynamically separate string input into different variables? For instance, if I have
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//pseudo of course

string nums = "";
string letts = "";
string temp;

while (cin){
if alpha
>> temp
letts += temp
if digit
>> temp
nums += temp

So that the input of R1u2n4 would be 
nums = 124
letts = Run

???

Thank you.
Last edited on
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
#include <iostream>
#include <string>
#include <locale>

int main()
{
    std::string digits ;
    std::string alpha ;
    std::string others ;

    // https://en.cppreference.com/w/cpp/io/ios_base/getloc
    const auto input_locale = std::cin.getloc() ;

    std::cout << "enter a string: " ;
    char c ;
    // for each character read from stdin till a white space is read
    while( std::cin.get(c) && !std::isspace( c, input_locale ) )
    {
        // classify as per the input locale and append to appropriate string
        if( std::isdigit( c, input_locale ) ) digits += c ; // decimal digits
        else if( std::isalpha( c, input_locale ) ) alpha += c ; // alphabetic characters
        else others += c ; // everything else
    }

    std::cout << "\ndigits: " << digits << '\n'
              << " alpha: " << alpha << '\n'
              << "others: " << others << '\n' ;
}

http://coliru.stacked-crooked.com/a/7a7ce0a7f56573cd
Awesome!

Thanks not only for the documentation(because I do actually read everything recommended to me), but a working example as well. This is exactly what I was hoping for.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
   string test = "R1u2n4";
   string letters, digits;
   copy_if( test.begin(), test.end(), back_inserter( letters ), ::isalpha );
   copy_if( test.begin(), test.end(), back_inserter( digits  ), ::isdigit );
   cout << test << '\n' << letters << '\n' << digits << '\n';
}


R1u2n4
Run
124
Last edited on
Topic archived. No new replies allowed.