如何在 C++ 中将字符串解析为 int? [英] How to parse a string to an int in C++?

查看:37
本文介绍了如何在 C++ 中将字符串解析为 int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将字符串(以 char * 形式给出)解析为 int 的 C++ 方法是什么?强大而清晰的错误处理是一个优点(而不是返回零).

What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).

推荐答案

在新的 C++11 中有用于此的函数:stoi、stol、stoll、stoul 等等.

In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.

int myNr = std::stoi(myString);

它会在转换错误时抛出异常.

It will throw an exception on conversion error.

即使这些新函数仍然存在同样的问题,正如 Dan 所指出的:他们很乐意将字符串11x"转换为整数11".

Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11".

查看更多:http://en.cppreference.com/w/cpp/string/basic_string/斯托

这篇关于如何在 C++ 中将字符串解析为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆