How do I convert a string containing say "12", into an integer 12 using C++??? I have to use the 'getline' function to grab data from a file, and 'getline' only lets you grab characters and strings.. any thoughts?
How do I convert a string containing say "12", into an integer 12 using C++??? I have to use the 'getline' function to grab data from a file, and 'getline' only lets you grab characters and strings.. any thoughts?
see FAQ -- I;m certain you will find the answer there. I could easily tell you, but you would miss out all the fun and extra knowledge of looking it up yourself. Happy hunting
Hint: see std::stingstream
atoi! thats what i thought to use, but the way i had it set up wasnt working right... thanks anyways!
Actually the correct answer is: FAQ > How do I... (Level 1) > Convert a string to a int (C++)
that is not a c++ solution. atol() is a C function, It will work, but will not satisfy your orginal request.Originally Posted by bcianfrocca
Last edited by Ancient Dragon; 09-08-2005 at 08:50 PM.
You're contradicting yourself. It'll work, but it won't work. In reality, it'll work just fine if the string represents a valid integer. atoi() and it's kin are all valid C++, even if they are inherited from C. It really doesn't matter whether the solution is unique to C++ or inherited as long as it works. If you're not keen on wrapping stringstream or using something like boost::lexical_cast then it's more awkward than atoi or strtol IMO.It will work, but will not satisfy your orginal request.
Just because I don't care doesn't mean I don't understand.
No I did not contricit myself. The OP specifically stated a c++ solution. atoi() is a C solution. Just because c++ supports it doesn't make it a c++ solution any more than printf(), sprintf() gets() or any other C standard library functions.Originally Posted by Narf
atoi() works the way it is documented to work. I personally would use it to make the conversion, but then I didn't ask the original question.
If the standard supports it, it's a C++ solution. Any other opinion is strictly based on what the person thinks a "C++ solution" should be. As long as we agree that it's impossible to be wrong in light of subjective opinions, we're both right and it's all good.Just because c++ supports it doesn't make it a c++ solution any more than printf(), sprintf() gets() or any other C standard library functions.
Just because I don't care doesn't mean I don't understand.