Search code examples
c++stringstreamcingetline

How to extract next integer in an arbitrary position in string?


My code is below, I'm working on a simple text editor. The user needs to be able to input the following format:

I n
//where n is any integer representing the line number.

I used a switch statement below to see what the first character they typed is, but in case 'I' (insert) and case 'D'(delete) I need to be able to extract the integer they typed after that.

For example:

D 16 // deletes line 16
I 9 // Inserts string at line 9
L // lists all lines

I have tried a few different things but nothing works smoothly so I was wondering if there is a better way to do this.

void handle_choice(string &choice)
{   
    int line_number;

      // switch statement according to the first character in string choice.
    switch (choice[0]) 
    {

    case 'I':

       // code here to extract next integer in the string choice

      break;

    case 'D':

      break;

    case 'L':

      break;

    case 'Q':

      break;

    default:
      break;
    }

I tried a few different things like getline() and cin << but I can't get it to work properly in case the user doesn't input the line in that specific format and I was wondering if there is a way.

Thanks.


Solution

  • #include <cctype>
    #include <string>
    using namespace std;
    
    // This function takes the whole input string as input, and
    // returns the first integer within that string as a string.
    
    string first_integer(string input) {
       // The digits of the number will be added to the string
       // return_value. If no digits are found, return_value will
       // remain empty.
       string return_value;
       // This indicates that no digits have been found yet.
       // So long as no digits have been found, it's okay
       // if we run into non-digits.
       bool in_number = false;
    
       // This for statement iterates over the whole input string.
       // Within the for loop, *ix is the character from the string
       // currently being considered. 
       for(string::iterator ix = input.begin(); ix != input.end(); ix++) {
         // Check if the character is a digit.
         if(isdigit(*ix)) {
             // If it is, append it to the return_value. 
             return_value.push_back(*ix);
             in_number = true;
         } else if(in_number) {
             // If a digit has been found and then we find a non-digit
             // later, that's the end of the number.
             return return_value;
         }
       }
       // This is reached if there are no non-digit characters after
       // the number, or if there are no digits in the string. 
       return return_value;
    }
    

    Within your switch statement, you would use it like this:

    case 'I':
         string number = first_integer(choice);
         // Convert the string to an int here.