Jump to content
  • Advertisement
Sign in to follow this  
Kevn

better way to extract number from string?

This topic is 2513 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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();

Share this post


Link to post
Share on other sites
Advertisement

ifstream fs( "test.txt" );
if ( !fs )
return;

fs.seekg( 0, ios::end );
int sz = fs.tellg();
fs.seekg( 0, ios::beg );

char* file = new char[sz];
in.read( file, sz );

vector<int> data;
char* current = file;
char* previous = file;
char* end = file + sz;
int i;
while ( current < end ) {
previous = current;
i = strtol( current, &current, 10 );
if ( previous == current )
current ++;
else
data.push_back( i );
}

delete[] file;
</int>

EDIT:
Oops, didn't see that the integers needed to be prefixed with 'i'.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!