Click here to Skip to main content
15,909,051 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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.
Posted
Comments
Jochen Arndt 27-Aug-13 2:57am    
See http://www.cplusplus.com/reference/cstdlib/atoi/
Stefan_Lang 27-Aug-13 3:54am    
As others have pointed out, you need to use the C function atoi(), as there is no specific C++ function for the same purpose (at least not in the standard).

If this does not work for you, you may be using it wrong. Make sure that the argument you pass to atoi() is a single byte C-style ASCII character string terminated by a 0-byte. If your project uses Unicode, or you are using a specific string type internally,, you may need to convert your string first before passing it to atoi.

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

Hope this helps.
 
Share this answer
 
Comments
sajid zafar_Iqbal 27-Aug-13 3:03am    
i am doing the code in eclipse and i have done it already but it doesn't work i have included libraries <stdlib.h> etc to use this but still it doesnt works.Kindly give me the appropriate soluiton.
Thomas Daniels 27-Aug-13 3:04am    
What do you mean by "it doesn't work"? Do you get an error? If so, can you provide the error text please?
You dind't give any detail about your scenario.
Anyway you may find these documentation pages useful:

strtol is useful if the numeric base is not 10, e.g. hexadecimal representation.


You may also use a strstream object for the purpose:
C++
strstream s;
int i;
s << "123";
s >> i;
 
Share this answer
 
v2
Comments
Thomas Daniels 27-Aug-13 3:16am    
+5!
CPallini 27-Aug-13 3:31am    
Thanks, and have my 5 too.
Thomas Daniels 27-Aug-13 3:32am    
Thank you!
Stefan_Lang 27-Aug-13 3:55am    
Good point about using strstream. Have a 5!
CPallini 27-Aug-13 4:00am    
Thank you.
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.

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900