# Finding number in string

• 08-03-2009
Ducky
Finding number in string
Would there be an easier way to find and print out one number from a string without knowing the number?
For example the fifth number.

Code:

```#include <iostream> #include <string> using namespace std; int main() {           string port1;           size_t found;           int port1int;           string ftpmessage = " (66,220,9,50,27,99).";                     found  = ftpmessage.find(",");           found  = ftpmessage.find(",",found+1);           found  = ftpmessage.find(",",found+1);           found  = ftpmessage.find(",",found+1);           for(int i=1; i<4; i++)           {               port1 = ftpmessage.substr(found+1,i);               if (port1.find(",") != string::npos) break;           }           cout << "port1: " << port1 << endl;           return 0; }```
• 08-03-2009
tabstop
Is it possible that by "without knowing the number" you really mean "with the number in a variable"? If so, there are such things as loops, for when you want to repeat something a certain number of times.
• 08-03-2009
Ducky
Thank you Tabstop!

Im sorry i meant the number after the fourth comma.

So i guess i should put this in a loop:

Code:

``` found  = ftpmessage.find(",");           found  = ftpmessage.find(",",found+1);           found  = ftpmessage.find(",",found+1);           found  = ftpmessage.find(",",found+1);```
I was thinking about a function that finds the fourth comma and gives back its position
or the characters after it, that would save the place for a loop.
• 08-03-2009
tabstop
If it's always the fifth number (== after the fourth comma) then I'm not sure you have a question, since that's what you started with.

Anyway, as a suggestion, because I've been in a stringstream frame of mind for the last little while, why not use a stringstream? You can initialize your stringstream with the string you've got, and peel off numbers with >> until you get to the one you want. (You'll either have to read the comma, or there's probably some magic you can do to make >> think (at least temporarily) that comma is a whitespace character so it will automatically separate and be removed.)
• 08-03-2009
Ducky
Good idea! Thanks!
• 08-03-2009
laserlight
Quote:

Originally Posted by tabstop
(You'll either have to read the comma, or there's probably some magic you can do to make >> think (at least temporarily) that comma is a whitespace character so it will automatically separate and be removed.)

I wrote this token matching manipulator that could be used for such purposes.
• 08-03-2009
Ducky
Thank you Laserlight, i look into it.