![](/img/trans.png)
[英]C++ How to convert what I thought was a string into an int? Trying to use stoi, but will use whatever works
[英]How to use a stoi, and return false if the string has a letter in c++?
所以,我在 C++ 中有这段代码,需要使用 stoi 来测试字符串 (a) 是否有字母,如果没有,则将数字发送到 int,如果有则返回 false。
我的代码
void main(){
string a = "a1321";
int b;
if (stoi(a)){
b = stoi(a);
cout << b << endl;
}
else cout << "ERROR"<< endl;
system("pause");
}
任何人都可以帮忙吗?
由于stoi
在解析时返回整数值,因此您不能直接使用返回值来检查正确性。
您可以捕获std::invalid_argument
异常,但它可能太多了。 如果你不介意使用strol
C 函数而不是std::stoi
你可以做类似的事情
bool isNumber(const std::string& str)
{
char* ptr;
strtol(str.c_str(), &ptr, 10);
return *ptr == '\0';
}
它利用了函数将第二个char**
参数设置为传递的字符串中的第一个非数字字符的事实,对于只包含数字的字符串,它应该是 '\\0' 。
你可以这样写函数:
bool try_stoi(int & i, const string & s){
try {
size_t pos;
i = stoi(s, &pos);
return pos == s.size();
}
catch (const std::invalid_argument&) {
return false;
}
}
//使用这段代码
int main() {
string a;
cin >> a;
try {
int b;
b = stoi(a);
cout << b;
}
catch (exception e) {
cout << "string not converted";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.