如何在c ++中将字符串转换为int

如何在c ++中将字符串转换为int

问题描述:

我是c ++的新手,我已经尝试了很多将字符串转换为int但我没有这样做。请提前给我一个简短的代码示例。

i am new to c++ and i have tried a lot to convert string into an int but i am failed to do so.Kindly give me a short code example thanks in advance.

尝试:

Try:
std::string str = "100";
int i = atoi(str.c_str());



希望这有帮助。


Hope this helps.


你没有提供有关你的场景的任何细节。

无论如何你可能会发现这些文档页面很有用:
You dind't give any detail about your scenario.
Anyway you may find these documentation pages useful:
  • atoi, _atoi_l, _wtoi, _wtoi_l[^].
  • strtol, wcstol, _strtol_l, _wcstol_l[^]
strstream s;
int i;
s << "123";
s >> i;


sscanf [ ^ ]也是一种广泛使用的替代方案。 />


如果从字符串中解析数字,则可能需要处理2种不同类型的错误:

1.转换是否成功? (某些实现不处理溢出)

2.从字符串的左侧处理了多少个字符?有些函数可以静默地允许你将乱码字符放在字符串中数字的右侧,而那些解析器函数只是忽略垃圾。如果你必须严格而不允许垃圾,那么你必须使用 strtol [ ^ ]可帮助您检测已使用字符数的功能。



编辑:strtol还具有能够使用任意基数解析数字的优点:它也可以解析八进制数,六进制数。
sscanf[^] is also a widely used alternative.

In case of parsing in a number from a string you may have to handle 2 different kind of errors:
1. Was the conversion successful? (some implementations don't handle overflow)
2. How many characters were processed from the left side of the string? Some functions silently allow you to put garbage characters to the right side of the number in the string and those parser functions simply ignore the garbage. If you have to be strict without allowing garbage then you have to use the strtol[^] functions that helps you to detect the number of used characters.

strtol also has the advantage of being able to parse numbers using arbitrary base: its possible to parse octal, hexa numbers too.