How to concatenate a std::string and an int

In alphabetical order: std::string name = “John”; int age = 21; std::string result; // 1. with Boost result = name + boost::lexical_cast<std::string>(age); // 2. with C++11 result = name + std::to_string(age); // 3. with FastFormat.Format fastformat::fmt(result, “{0}{1}”, name, age); // 4. with FastFormat.Write fastformat::write(result, name, age); // 5. with the {fmt} library result = fmt::format(“{}{}”, … Read more

C++ convert hex string to signed integer

use std::stringstream unsigned int x; std::stringstream ss; ss << std::hex << “fffefffe”; ss >> x; the following example produces -65538 as its result: #include <sstream> #include <iostream> int main() { unsigned int x; std::stringstream ss; ss << std::hex << “fffefffe”; ss >> x; // output it as a signed type std::cout << static_cast<int>(x) << std::endl; … Read more

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package. Example: BigInteger reallyBig = new BigInteger(“1234567890123456890”); BigInteger notSoBig = new BigInteger(“2743561234”); reallyBig = reallyBig.add(notSoBig);

Display number with leading zeros

In Python 2 (and Python 3) you can do: number = 1 print(“%02d” % (number,)) Basically % is like printf or sprintf (see docs). For Python 3.+, the same behavior can also be achieved with format: number = 1 print(“{:02d}”.format(number)) For Python 3.6+ the same behavior can be achieved with f-strings: number = 1 print(f”{number:02d}”)

How can I convert a std::string to int?

In C++11 there are some nice new convert functions from std::string to a number type. So instead of atoi( str.c_str() ) you can use std::stoi( str ) where str is your number as std::string. There are version for all flavours of numbers: long stol(string), float stof(string), double stod(string),… see http://en.cppreference.com/w/cpp/string/basic_string/stol

How can I check if a string represents an int, without using try/except?

with positive integers you could use .isdigit: >>> ’16’.isdigit() True it doesn’t work with negative integers though. suppose you could try the following: >>> s=”-17″ >>> s.startswith(‘-‘) and s[1:].isdigit() True it won’t work with ‘16.0’ format, which is similar to int casting in this sense. edit: def check_int(s): if s[0] in (‘-‘, ‘+’): return s[1:].isdigit() … Read more