Forcing String to int Function to Consume Entire String

前端 未结 2 816
青春惊慌失措
青春惊慌失措 2020-12-04 01:59

Given a string that should represent a number, I\'d like to put it into a conversion function which would provide notification if the whole string did not convert.<

2条回答
  •  有刺的猬
    2020-12-04 02:58

    Alternatively you can use std::istringstream as you mentioned, but check to make sure it parsed to the end of the stream. Assuming you have a constant reference, you could do something like the following

    T parse(const std::string& input) {
        std::istringstream iss(input);
            T result;
            iss >> result;
            if (iss.eof() || iss.tellg() == int(input.size())) {
                return result;
            } else {
                throw std::invalid_argument("Couldn't parse entire string");
        }
    }
    

    The benefit of this approach is that you parse anything that overloads operator>>. Note: I'm not entirely sure if the condition is enough, but with my testing it seemed to be. For some reason the stream would get a failure marking if it parsed to the end.

提交回复
热议问题