Jump to content

  • Log In with Google      Sign In   
  • Create Account

better way to extract number from string?


Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.


  • You cannot reply to this topic
3 replies to this topic

#1   Members   -  Reputation: 165

Like
1Likes
Like

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


#2   Moderators   -  Reputation: 9433

Like
1Likes
Like

Posted 23 January 2012 - 02:20 PM

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'.
gzip: H4sIAAAAAAAEAG1QTUvEMBC991e8nvaiFfYoS7yo sLCo6MnjtJ1ugmkiyWRL/72z3T1YEQIJ8z4zA2Xp yPvt1qBpGrRFIJZkk9FyRyUzHCbKIHgn4hnZOrm1 TD0mG0HCCs+QGDGWziKXI6Wm2n++GYwUVH2mrGEE PnGCVQ8K8+JYfXA6URDEQfMZh5h6g5eoAlWJdeEI bbH2qYZf7XMUfw8f/Q0oMeZYNL9/WHF0uFEshvMr XYujd9SycFb+F18QcSOvlJauZ8ejqevdnV7/d550 e0t6prmunh73Bu+vz4c/XUeOQXfJgvKNkhf95U8/ Dtgmy5IBAAA=

#3   Moderators   -  Reputation: 11404

Like
5Likes
Like

Posted 23 January 2012 - 02:22 PM

*
POPULAR


  while (infile) {

    std::istream::int_type c = infile.get();

    if (c == 'i') {

      std::istream::int_type next = infile.peek();

      if (isdigit(next)) {

        int i;

        infile >> i;

        std::cout << i << std::endl;

      }

    }

  }



#4   Members   -  Reputation: 165

Like
0Likes
Like

Posted 23 January 2012 - 03:40 PM

Awesome, thank you!




Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.




PARTNERS