Is there a TryParse equivalent in C++ (gcc)?

前端 未结 4 2045
滥情空心
滥情空心 2021-01-15 15:48

Is there a equivalent of TryParse in C++(gcc) ?

I would like to parse a string which may contain (+31321) and store it as long. I know phone numbers are stored as st

4条回答
  •  余生分开走
    2021-01-15 16:18

    the input extraction operator >> (i hope it's an acceptable name) applies and returns a stream&, that has a bool operator, meaning the extraction has been succesfully attempted. For instance, from the Cubbi answer:

    ...
        std::istringstream s("+31321");
        long n;
        if (s >> n)
          std::cout << n << '\n';
    ....
    

    This will succed, of course, given the appropriate content of s.

    Somewhat different (easier but not type safe) also the scanf family has practical tools available in c++ as well c. You could of course write the example this way:

    ...
        long n;
        if (sscanf("+31321", "%d", &n) == 1)
          std::cout << n << '\n';
    ...
    

    A subset of regular expressions make this rather powerful: for instance to match a comma separed multi fields with left space trimming:

       if (sscanf("a,b,c", " [^,], [^,], [^,]", a,b,c) == 3) ...
    

提交回复
热议问题