[英]How can I check if the data in a string is a number on C++?
I am new to C++.我是 C++ 的新手。 If the user enters a string with different information that is separated by a delimiter, eg #
, and I use string manipulation to extract the info into different variables, how would I check if one of the string variables contain a number?如果用户输入具有不同信息的字符串,该字符串由分隔符分隔,例如#
,并且我使用字符串操作将信息提取到不同的变量中,我将如何检查其中一个字符串变量是否包含数字? In the simplest way possible (beginner).以最简单的方式(初学者)。
eg.例如。
John#Doe#51
Name - John
Surname - doe
Age - 51
How do I make sure that the user typed a number for age?如何确保用户输入了年龄数字?
You can use std::stoi()
or related function checking for errors, or put the extracted string into a std::istringstream
and read an integer from it using operator>>
checking for errors.您可以使用std::stoi()
或相关的 function 检查错误,或将提取的字符串放入std::istringstream
并使用operator>>
检查错误从中读取 integer。
Or, just use std::istringstream
to parse the entire delimited string to begin with.或者,只需使用std::istringstream
来解析整个分隔字符串。 No need to extract substrings and convert them manually.无需提取子字符串并手动转换它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.