Jump to content

  • Log In with Google      Sign In   
  • Create Account

Kevn

Member Since 22 Feb 2009
Offline Last Active Aug 06 2014 05:09 PM

#4905544 better way to extract number from string?

Posted by Kevn on 23 January 2012 - 02:06 PM

Hey, I was wondering if there is a better/more efficient way of going about extracting any number that follows 'i' in a file. So lets say the document has the following content : "Hello, this is a random document... try to extract i1 i34 i405 i2 from this document". So by the end of the extraction you would have the numbers 1, 34, 405, and 2.

The way I am currently doing it is:
string filename, line;
int test = 0;
ifstream infile(filename);
if (!infile){
	cout << "Could not open file" << endl;
	return 1;
}
while (getline(infile, line))
{
	for (string::iterator it = line.begin(); it < line.end(); it++)
	{
		 if (*it == 'i'){
			  it++;
			  test = 0;
			  while (*it > 47 && *it < 58){
					test = test * 10;
					test = test + (*it - '0');
					it++;
				}
				cout << test << " ";
				it--;
			}
	  }
}
infile.close();



PARTNERS