Question about strings!


Hello I have a question!
Let's say that I have :

std::string words[3] = { "guy21", "town6", "1street" };

How do I get the numbers 21,6,1 out as int so that I can work with them?
For example line them up from smallest to biggest : 1,6,21

Thanks in advance ! :)
Last edited on
string words = ["guy21" , "town6" , "1street"];
I got no idea what this is, but it certainly aint c++.

std::string words[3] = { "guy21", "town6", "1street" };

You can loop through all the characters in the strings, and use this function - http://www.cplusplus.com/reference/cctype/isdigit/

If you happen to find a digit, then convert it to an integer - http://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c

It's gonna be a bit harder to find "21" rather than a single digit. There is no way c++ knows that you want 21 together. You'll need to figure that out yourself.
Last edited on
If all the digits in the string are consecutive you can use a combination of the std::string find_first_of(), std::string.substring() to isolate the digits for further processing.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <iostream>

using namespace std;

int main() 
{
stringstream ss;
string input = "4a b c 4 e";
ss << input;
int found;
string temp;

while(getline(ss, temp,' ')) {
    if(stringstream(temp)>>found)
    {
        cout << found << endl;
    }
}
return 0;
}
Last edited on
Topic archived. No new replies allowed.