What is the shortest way to check if a string contains the character “-” or it contains only numbers?
Edit: And how would I do it in C without std::string? Which one is better?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
std::stringhas a member function,find, which can be used to search for a character or substring. It returnsstd::string::nposif the search character or substring is not found.One straightforward way to test whether a string contains only digits is to use the
find_first_not_ofmember function with the search list"0123456789". If it returnsstd::string::npos, the string contains only digits; if it returns any other value, there is some other, nondigit character in the string.