GuillemVS
GuillemVS

Reputation: 366

How to detect if the whole string wasn't parsed with c++

I'm trying to parse a string to detect if it is a number or if it is a name, etc. And to do it I'm putting examples like "10 ms": it parses the 10 only, without returning an error. What I want to do is to get if the whole string can be parsed or not, not only a part of it.

Here is my code:

string s = "10 ms";
bool number = true;
try {
   stof(s, nullptr);
} catch (invalid_argument){
   number = false;
}

It returns that is a number. And the returned number from stof is 10. I have also tried using catch(...), same problem.

Upvotes: 1

Views: 138

Answers (1)

JVApen
JVApen

Reputation: 11317

Looking at the documentation of std::stof, it has 2 arguments, of which one is an output argument.

This can be used the following way:

#include <string>
#include <iostream>

int main(int, char**)
{
    try
    {
        std::string s = "10 ms";
        bool number = true;
        std::size_t nofProcessedChar = 0;
        auto nr = std::stof(s, &nofProcessedChar);
        std::cout << "found " << nr << " with processed " << nofProcessedChar << std::endl;
        auto allCharsProcessed = nofProcessedChar == s.size();
        std::cout << "all processed: " << allCharsProcessed << std::endl;
    }
    catch(const std::invalid_argument &)
    {
        std::cout << "Invalid argument " << std::endl;
    }
    catch (const std::out_of_range &)
    {
        std::cout << "Out of range" << std::endl;        
    }
}

Code at compiler explorer

As you can see in the output

found 10 with processed 2
all processed: 0

It prints 0 for all processed, which is the numeric casting value of bool.

Upvotes: 3

Related Questions