1

So, I'm asking a user to input a fraction in the form of this:

+3 3/4

I know I can use a search to find where the first instance of something happens, but how do I actually take whats before it? Example: I can tell it to search for white space, but how can I tell it to grab what is before it and save it into a variable?

Would it be easier to use an array of characters or can a string work?

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by wyett
1

If you use string, then use find() to locate the space, and substr() to extract the characters from position 0 to the location returned by find().

0

I know I can use a search to find where the first instance of something happens, but how do I actually take whats before it?

I see that you seem to be interested in using <string> class member functions for your parsing needs. May I suggest the following which uses find() and substr():

string expression = "+3 3/4";
string terms[10];
int prev = -1, curr = -1;
int i=0;

while(curr != string::npos)
{
     prev = curr;
     curr = expression.find(' ');
     if(curr != string::npos)
     {
          //Feel free to make any adjustments you need to extract the desired substring
          terms[i] = expression.substr(++prev, (curr-prev));
     }
     i++;
}

This may or may not be specifically what ye' are asking for, but should be able to point ye' in the right direction. In the above example, I obtained the first occurance of a white space, then stepped forward one element and extracted a "term" substring which I stored into the terms[] array.. feel free to affect the substr() arguments to return a substring of your chosing.

The above code is untested and may contain easy to fix errors. It is intended to be a suggestion only. Suggestions for improvement are always welcome.

Edited by Clinton Portis: ninjas of coding goodness.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.