Checking float inside string and return result?

I have a text file that I am binding to a string. The file looks like this:0.2abc 0.2 .2abc .2 abc.2abc abc.2 abc0.20 .2 . 20

I want to check the result, then parse it to split the float. Result:0.2 0.2abc 2 20 2abc abc0.20 abc

This is ruled out: check if there are 2 digits (before and after "." (Full stop)) with char or not. If only 1 site '.' digit '.' will be a complete stop.

How can I parse STRING to split the result? I used an iterator to check the '.' and him, but still stuck.

-1


a source to share


4 answers


The first thing you need to do is split the input words. Simple, just don't use .getline () but instead rely on `while (cin -> strWord) {/ * do things with the word * /};

Second, sooner or later start writing the wrong input words: words of 2 characters or less, with more than one, .

or with the .

first or last.



Now you know what .

is somewhere in between. find () will give you an iterator. ++ and - give you the next and previous iterators. * gives you the character that the iterator is pointing to. isdigit () tells you if this character is a digit. Add the ingredients together and you're done.

+1


a source


Sounds like some of the rather tricky tips above - and not necessarily helpful.

Your question does not make it completely clear what the final result should look like. Do you need an array of floating point numbers? Do you just need an amount? Do you want to print the results?

If you need help with your homework, the best policy is to post your own attempt and then others can help you improve it, make it work.



One approach that might help is to try to split the string into substrings (tokens) and discard garbage.

  • Write a function that takes a character and returns true (this is part of a floating point number) or false (it is not).
  • Scan along a string using an iterator or index.
  • As long as the current char is not part of the token, pass it.
  • If you find a char token and the current char is part of the token, copy it to another string
  • etc .. to get all floating point substrings.
  • Then you can use std :: stringstream or :: atof () to convert.

You have something like this that you can do.

+1


a source


sounds like you can use some kind of regex to extract your number.

Try this regex to extract floats in a string.

[0-9]+\.[0-9]+

      

Please be aware that this will not fetch integer values. those. 234abc

I don't know if there is a built-in way to use regex in C ++, but I found this library with a quick google search that allows regex to be used in C ++

0


a source


It looks like you should look at the Interpreter design pattern.

Or you can use the "State" Design Pattern and do it manually.

There should be many examples on the internet.

0


a source







All Articles