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?

Recommended Answers

All 3 Replies

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

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.

Thank you both. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.