🔒 Locked
String to Integer Cast?
Advertisement
Original Post
For one, I never did understand casting from one variable type to another, because I have never really needed them in C++. Now, I am faced with a problem: I am trying to cast from a string to an integer, but like I stated, I have never done so before. Is the format MyIntVar = *MyStringVar? I tried this and many other things, but for some reason, I remember it having to do with the asterisk somewhere.
If you mean you want to convert a string to an int you can use boost::lexical_cast.
If you really mean cast, then that just doesn't make much sense.
If you really mean cast, then that just doesn't make much sense.
Quote:
Original post by orcfan32
I think taking one variable type to another is called casting, but I'm not sure. I really don't want to get involved in a library as what I'm working on is a very small project.
Casting just changes the type identifier from one to the other, it doesn't actually convert it (at least, that's what people usually mean when they say "casting"). You want a function which converts it from one type to another, something like this could work:
#include <sstream>template<typename Type1, typename Type2>Type2 lexicalCast(Type1 x) { std::stringstream stream; Type2 result; stream << x; stream >> result; return result;}
There often is a nuance of meaning between "cast" and "conversion" when talking about completely unrelated types. Like strings and integers.
If you say "cast", you may very well be interpreted as wanting to reinterpret the string as if it had been an int all along, without concern for its true meaning. The resulting integer would definitely not be the same as the one that the string may represent. If you do int i = *(const int*)"1234";, it'll be a cast, but i will not contain the number 1234.
Now, if you say you want to convert your string into an int, people will be much more likely to understand you want to turn the string "1234" into the number 1234. This is something you can do in a number of ways, the simplest of which being boost::lexical_cast (yes, I know, it has "cast" in it, bite me, it is a 'cast' function explicitely designed to do such conversions), as SiCrane already has mentioned.
If you say "cast", you may very well be interpreted as wanting to reinterpret the string as if it had been an int all along, without concern for its true meaning. The resulting integer would definitely not be the same as the one that the string may represent. If you do int i = *(const int*)"1234";, it'll be a cast, but i will not contain the number 1234.
Now, if you say you want to convert your string into an int, people will be much more likely to understand you want to turn the string "1234" into the number 1234. This is something you can do in a number of ways, the simplest of which being boost::lexical_cast (yes, I know, it has "cast" in it, bite me, it is a 'cast' function explicitely designed to do such conversions), as SiCrane already has mentioned.
Quote:
Original post by orcfan32
I think taking one variable type to another is called casting, but I'm not sure. I really don't want to get involved in a library as what I'm working on is a very small project.
You you move data from one type into a variable of a different type, it is called casting. For instance,
int foo = 32;
char bar = foo;
foo and bar both equal 32.
I'm assuming that you want to take numerical data in text format (string) and convert it to an actual integer value. This is called a conversion since the data is changing format. You can write your own algorithm to do the conversion (which may be buggy) or you can use boost::lexical_cast as SiCrane suggested. It's pretty straightforward to use and robust.
orcfan32,
Think of casting only when you are using pointers. If you have a virtual 'Object' class, and you have a list of objects, you can cast the pointer into one of the child classes of 'Object'. This is useful if you know the RTTI for the object at a certain time period, then you can use the functions that belong to that converted type (if there are any).
Casting the known compiler types (int, float, double) has alot of drawbacks: lots of truncations and stuff happen underneath. Doing a type cast of the nature your talking about will end up using the non-ascii values of the ascii character as the integer your converting into.
As for converting string to ascii, if you know what you want to convert it into you can use the functions in the math.h file, 'atoi', 'atof', etc.
-brad
Think of casting only when you are using pointers. If you have a virtual 'Object' class, and you have a list of objects, you can cast the pointer into one of the child classes of 'Object'. This is useful if you know the RTTI for the object at a certain time period, then you can use the functions that belong to that converted type (if there are any).
Casting the known compiler types (int, float, double) has alot of drawbacks: lots of truncations and stuff happen underneath. Doing a type cast of the nature your talking about will end up using the non-ascii values of the ascii character as the integer your converting into.
As for converting string to ascii, if you know what you want to convert it into you can use the functions in the math.h file, 'atoi', 'atof', etc.
-brad
I'm sorry if I am mistaken, but couldn't you just use atoi() ? It doesn't involve a large library or anything.
What are you trying to accomplish? Why would you want to do that?
MyIntVar will result in 155, the ASCII numeric value for the character 's'.
Observe that no casting is needed because by definition, a character, is simply a small integer - In C.
Maybe what you meant to do was convert a string of digits to an int?
look into atoi(). Again, this is purely C.
Quote:
int MyIntVar;
char *MyStringVar = "string constant";
MyIntVar = *MyStringVar;
MyIntVar will result in 155, the ASCII numeric value for the character 's'.
Observe that no casting is needed because by definition, a character, is simply a small integer - In C.
Maybe what you meant to do was convert a string of digits to an int?
look into atoi(). Again, this is purely C.
Quote:
Original post by ussnewjersey4
I'm sorry if I am mistaken, but couldn't you just use atoi() ? It doesn't involve a large library or anything.
Quote:
Original post by xeddiex
Maybe what you meant to do was convert a string of digits to an int?
look into atoi(). Again, this is purely C.
Here's one to think on: How do you know when atoi() wasn't able to get a valid number out of the string? Don't answer too quickly...
boost::lexical_cast is flexible, full-featured, safe, and easy. Using a std::stringstream is flexible, and safe, and still easy but marginally less so. Using atoi() is just easy.
Cheers,
Twilight Dragon
Quote:
Original post by Roboguy
You want a function which converts it from one type to another, something like this could work:
That doesn't handle certain cases like casting an object to a string when the object's text representation contains spaces. You need a specialization for when the type being returned is a string, wstring or other basic_string type. Which boost::lexical_cast does for you.
Quote:
Original post by TDragon Quote:
Original post by ussnewjersey4
I'm sorry if I am mistaken, but couldn't you just use atoi() ? It doesn't involve a large library or anything.Quote:
Original post by xeddiex
Maybe what you meant to do was convert a string of digits to an int?
look into atoi(). Again, this is purely C.
Here's one to think on: How do you know when atoi() wasn't able to get a valid number out of the string? Don't answer too quickly...
boost::lexical_cast is flexible, full-featured, safe, and easy. Using a std::stringstream is flexible, and safe, and still easy but marginally less so. Using atoi() is just easy.
Cheers,
Twilight Dragon
When ever I use atoi in any of my programs, I let all digits but '0' reach atoi. If atoi returns 0, for failure, I know the value returned wasn't a 'valid number'. And the digit '0' is processed in a rightly manner either before, or after atoi. There's always a way around.
@The OP: If you're using C++. disregard my advice and use boost.
boost::lexical_cast is neat, but if you want to stick to the standard library:
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss;
ss.str("12");
int i;
ss >> i;
std::cout << i << std::endl;
}
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss;
ss.str("12");
int i;
ss >> i;
std::cout << i << std::endl;
}
int foo = 20;
char bar[100];
get int into string:
sprintf( bar, "%i", foo ); // %i = int %u = unsigned int etc... there are many more
get string into int:
foo = atoi(bar); // atoi = str -> int , atof = str->float ..
char bar[100];
get int into string:
sprintf( bar, "%i", foo ); // %i = int %u = unsigned int etc... there are many more
get string into int:
foo = atoi(bar); // atoi = str -> int , atof = str->float ..
I will never understand the popularity of atoi. Except for the very limited cases where you can guarantee aspects of the input you virtually have to parse the string yourself before you can use it safely:
Enigma
#include <cstdlib>#include <iostream>#include <boost/lexical_cast.hpp>int main(){ char const * strings[] = { "77", "0", "3l337", "thirteen", "12345678901234567890" }; for (int i = 0; i < 5; ++i) { int atoiResult = std::atoi(strings); std::cout << "atoi(" << strings << ") = " << atoiResult << '\n'; try { int lexicalCastResult = boost::lexical_cast< int >(strings); std::cout << "lexical_cast< int >(" << strings << ") = " << lexicalCastResult << '\n'; } catch (...) { std::cout << "lexical_cast< int >(" << strings << ") = not a valid int\n"; } }}Enigma
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement