如何解析一个字符串到C ++中的int? [英] How to parse a string to an int in C++?
本文介绍了如何解析一个字符串到C ++中的int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是C ++的方式解析一个字符串(给定为char *)到一个int?强大且清晰的错误处理是一种加号(而不是返回零)。
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 / stol
这篇关于如何解析一个字符串到C ++中的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文