Find the answer to your Linux question:
Results 1 to 3 of 3
I'm trying to get my program to go through the string typed in by the user and strip it of EVERYTHING but the numbers. I can't place my finger on ...
  1. #1
    Just Joined!
    Join Date
    May 2010
    Posts
    3

    Cool [SOLVED] deleting parts of a string

    I'm trying to get my program to go through the string typed in by the user and strip it of EVERYTHING but the numbers. I can't place my finger on what I'm missing. Help please?

    Code:

    Code:
    #include<iostream>
    #include<string>
    using namespace std ;
    
    int main()
    {
    	string myString ;
    
    	cout << "Please enter data: " ;
    	
    	getline( cin, myString ) ;
    
    	// disgard anything that's not an int
    	for ( int x = 0 ; myString.length() ; x++ )
    	if ( !isdigit( myString[ x ] ) )
    		myString.erase( x, 1 ) ;
    
    	// display contents
    	cout << myString << endl ;
    } // end main
    PS everything compiles ok, but I get a runtime error anytime I hit enter after entering any data.

  2. #2
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    I tried this and it appears to work...As you delete characters from your string it shrinks, so to correct for this --x.

    Code:
    #include<iostream>
    #include<string>
    using namespace std ;
    
    int main()
    {
    	string myString ;
    
    	cout << "Please enter data: " ;
    	
    	getline( cin, myString ) ;
    
    	// disgard anything that's not an int
    	for ( int x = 0 ; x < myString.length(); x++ )
    	if ( !isdigit( myString[ x ] ) )
    	{
    		myString.erase( x, 1 ) ;
    		--x;
    	}
    
    	// display contents
    	cout << myString << endl ;
    } // end main
    Make mine Arch Linux

  3. #3
    Just Joined!
    Join Date
    May 2010
    Posts
    3
    That solved it! I knew it was something small I was missing.

    Thanks a bunch dude!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...