Convert string to int using C++The string class is a very useful way to deal with strings when using c++. Sometimes, however, you run into conversion issues and you want to be able to convert a string which contains an integer into an int datatype. The trick to doing this conversion is simply to use the function atoi found in stdlib.h. But you must pass that function a char array and therefore you must use the c_str() method to convert your string class to a character array. The following code is an example of how you can convert string to int.
#include <stdlib.h>
#include <iostream.h> #include <string> int GetIntVal(string strConvert) { int intReturn; // NOTE: You should probably do some checks to ensure that // this string contains only numbers. If the string is not // a valid integer, zero will be returned. intReturn = atoi(strConvert.c_str()); return(intReturn); } That's that. Your string is now converted into an int. Author: DPAK Created: Dec 1 2005 Categories: C++ TechByte #99 Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.
Add a comment about this TechByteIf you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED. Other TechBytes: |
|

