-1

I know how to convert the string when it's just made up of integers, or it begins with ints. I am trying to convert to an integer when the string starts with a char in the beginning, or middle. I've tried running through a for loop, checking if (isdigit(str[i]) before trying stoi, stringstream, atoi, etc... None of them really work. I have the same problem even without the for loop. I've tried Googling my problem, but no luck. Any suggestions, or anything that I can try?

  • Could you give an example of what you are trying to achieve? – tourniquet_grab Mar 29 '15 at 15:53
  • 3
    Can you show us some examples of strings where you want to extract a number together with the expected results? There is no such thing as a one-size-fits-all parser. – 5gon12eder Mar 29 '15 at 15:54
  • You have gghftdghx124q7a5zq. What do you want to get? – n. m. could be an AI Mar 29 '15 at 15:55
  • In the example of gghftdghx124q7a5zq, I'd be trying to get 12475. I'm trying to create a calculator that accepts string input aswell as number to represent different things (example: when the user inputs "p5" it would to pi*5, because p represents pi). I just need help extracting the integers from the string. – katamaridamacy Mar 29 '15 at 16:05
  • 1
    Figure you could use regex for this. Or you should be able to loop through the string and if a char is a digit you can append it to a second string which will contains the extracted digits is string form. Then do your normal stoi. Do you have code to post? – Eissa Mar 29 '15 at 16:11

1 Answers1

2

You have to check character by character if it's a digit or not and, if it is, add it to a new string. In the end, you convert your new string to an int like you would normally. Look at the code below. Hope I could help!

string s = "pc2jjj10";
    char temp;
    string result;

    for (int i = 0; i < s.length(); i++){

        temp = s.at(i);

        if (isdigit(temp)){
            result.push_back(temp);
        }
    }

    int number = stoi(result);
maj
  • 48
  • 7