Make a int that could be passed as string

Started by
13 comments, last by King Mir 11 years, 2 months ago

C++11 introduced some new conversion functions for that exact purpose:

std::to_string() - Integers and float-types to std::string.

Also:

std::stoi() - std::string to int

std::stol() - std::string to long

std::stoul() - std::string to unsigned long

std::stof() - std::string to float

std::stod() - std::string to double

The function-name format is:

stof

s <to> f

string <to> float

Just like the pre-existing atoi() (where 'a' is for ASCII, 'char*' raw-string functions)

This is different from strtof() and the like. I have no clue what those functions do. smile.png

([Edit:] Ah, here's an explanation of strtof. I never knew about that function)

Inventing a hot water? Nah, id just use this...

Rereading c++11 is a good idea i see, thanks much.

Advertisement

Also boost::lexical_cast is nice for these kinds of things.

As was pointed out, helper functions are your friend or even just overloading functions to return different types depending on your needs.

Remember! More code just takes up more memory, which is very plentiful these days, if anything you only want to be worried about usability and performance on critical sections, so if something seems messy, write more code(to an extent anyway.)

That or write cleaner feeling code.


value = 0; //valid
value = 's';//invalid

I see a problem with these two lines. How do you have a class that accepts 0 (an int) and rejects 's' (an int)?

's' is a char in C++, so you'd need a function that takes a char and produces an error when passed something other than a digit. Or just always produces an error.

Ah, you're right. Character constants became of char type in C++. My mistake.

Yep, it's one of the subtle differences between C and C++. It means that code like this will have different results in the two languages.

int main(){
  return sizeof('a');
}

This topic is closed to new replies.

Advertisement