Cpp long int to string

Функция преобразования long long в string

Подскажите как можно преобразовать 16-значное число в string . Или для этого подойдет itoa() ?

Ответы (4 шт):

#include #include int main() < std::stringstream sstream; std::string snum; long long num = 999L; sstream > snum; // или snum = sstream.str() std::cout

Можно написать обобщенную функцию:

#include #include template std::string to_str(const T &obj) < std::stringstream sstream; sstream int main()

Обновление: пример на чистом C.

P.S. Все-таки, если хотите на чистом C, то не стоит писать в заголовке вопроса и в тегах "C++".

Имеется перегруженная стандартная функция с именем std::to_string , которую вы можете использовать для преобразования целочисленных значений (и значений с плавающей точкой) в строку.

Вывод программы на консоль следующий:

Sequence of numbers: -1, 2, -3, 4 
string to_string(int val); string to_string(unsigned val); string to_string(long val); string to_string(unsigned long val); string to_string(long long val); string to_string(unsigned long long val); string to_string(float val); string to_string(double val); string to_string(long double val); 

Имейте в виду, что если вы работаете с MS VC++ 2010, то у вас могут быть проблемы с неоднозначностью вызова функции, так как эта функция в MS VC++ определена не для всех указанных в списке типов.

Читайте также:  Optional params in java

Узнать, сколько десятичных знаков может храниться в числе вы можете с помощью класса std::numeric_limits . Например, следующая программа

#include #include int main() < std::cout ::digits10 ::digits10

в зависимости от платформы, где запущена программа, может иметь следующий вывод на консоль:

Для С++11 и старше самый простой вариант использовать функцию std::to_string

std::string ulonglongToStr(int64_t l, int base) < char buff[67]; // length of MAX_ULLONG in base 2 buff[66] = 0; char *p = buff + 66; const char _zero = '0'; if (base != 10) < while (l != 0) < int c = l % base; --p; if (c < 10) *p = '0' + c; else *p = c - 10 + 'a'; l /= base; >> else < while (l != 0) < int c = l % base; *(--p) = _zero + c; l /= base; >> return p; > std::string longlongtoStr(int64_t l, int base)

Источник

Convert Long to String in C++ | (3 ways)

In this article, we will learn about three different ways to convert a long to a string in C++ i.e.

  1. Using to_string() function
  2. Using stingstream
  3. Using Boost’s lexical_cast() function.

Let’s discuss them one by one.

Convert long to string using to_string()

C++ provides a function std::to_string() for converting values of different types to string type. We can use this to convert a long to string. For example,

#include #include using namespace std; int main() < long num = 102612; // Convert long to string string num_str = to_string(num); cout

We passed a long to the to_string() function, and it converted the given long to a string and returned the string object. If you pass a negative long to the to_string(), it will convert to a string with a minus symbol.

Frequently Asked:

Convert long to string using stringstream in C++

C++ provides a class stringstream, which provides a stream-like functionality. We can insert different types of elements in stringstream and get a final string object from the stream. Check out this example,

#include #include #include using namespace std; int main() < long num = 1789; stringstream stream; // Add long to the stream stream<Are you a C++ programmer eager to step up your game?

Master the intricacies of C++/C++11/C++20 with our handpicked list of the Best Courses to Learn Modern C++11, C++17 and C++20. Sharpen your skills, conquer complex algorithms, and stand out in your professional or academic sphere.

This isn't just about learning - it's about transforming into the programmer you aspire to be. So, why wait?

Your leap towards programming excellence is just a click away.

In the stringstream, we inserted a long, and the stream converted the long to string. Then, in the end, we requested a string object from the stream.

Convert long to string using boost::lexical_cast()

The C++ boost library provides a template function for data type conversion. It helps to convert elements from one data type to another. We can use that to convert a long to a string. For example,

#include #include #include using namespace std; using namespace boost; int main() < long num = 3456; // Convert long to string using boost library string str = lexical_cast(num); cout

We learned about three different ways to convert a long to a string in C++.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

std:: to_string

Let buf be an internal to the conversion functions buffer, sufficiently large to contain the result of conversion.

Contents

[edit] Parameters

[edit] Return value

A string holding the converted value.

[edit] Exceptions

May throw std::bad_alloc from the std::string constructor.

[edit] Notes

  • With floating point types std::to_string may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.
  • The return value may differ significantly from what std::cout prints by default, see the example.
  • std::to_string relies on the current locale for formatting purposes, and therefore concurrent calls to std::to_string from multiple threads may result in partial serialization of calls. C++17 provides std::to_chars as a higher-performance locale-independent alternative.

[edit] Example

#include #include int main() { for (const double f : {23.43, 1e-9, 1e40, 1e-40, 123456789.0}) std::cout  "std::cout: "  f  '\n'  "to_string: "  std::to_string(f)  "\n\n"; }
std::cout: 23.43 to_string: 23.430000 std::cout: 1e-09 to_string: 0.000000 std::cout: 1e+40 to_string: 10000000000000000303786028427003666890752.000000 std::cout: 1e-40 to_string: 0.000000 std::cout: 1.23457e+08 to_string: 123456789.000000

Источник

std:: to_string

Returns a string with the representation of val.

The format used is the same that printf would print for the corresponding type:

type of val printf equivalent description
int "%d" Decimal-base representation of val.
The representations of negative values are preceded with a minus sign (-).
long "%ld
long long "%lld
unsigned "%u" Decimal-base representation of val.
unsigned long "%lu
unsigned long long "%llu
float "%f" As many digits are written as needed to represent the integral part, followed by the decimal-point character and six decimal digits.
inf (or infinity) is used to represent infinity.
nan (followed by an optional sequence of characters) to represent NaNs (Not-a-Number).
The representations of negative values are preceded with a minus sign (-).
double "%f
long double "%Lf

Parameters

Return Value

Example

// to_string example // std::cout // std::string, std::to_string int main () < std::string pi = "pi is " + std::to_string(3.1415926); std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number"; std::cout '\n'; std::cout '\n'; return 0; >
pi is 3.141593 28 is a perfect number 

Exceptions

See also

sprintf Write formatted data to string (function) to_wstring Convert numerical value to wide string (function)

Источник

std::to_string

Может бросить std::bad_alloc из конструктора std::string .

Notes

  • С типами с плавающей точкой std::to_string может дать неожиданные результаты, так как количество значащих цифр в возвращаемой строке может быть нулевым, см. Пример.
  • Возвращаемое значение может значительно отличаться от того, что выводит std::cout по умолчанию, см. Пример.
  • std::to_string опирается на текущую локаль для целей форматирования, и поэтому одновременные вызовы std::to_string из нескольких потоков могут привести к частичной сериализации вызовов. C ++ 17 предоставляет std::to_chars как высокопроизводительную независимую от локали альтернативу.

Example

#include #include int main() < for (const double f : 23.43, 1e-9, 1e40, 1e-40, 123456789.>) std::cout "std::cout: " << f '\n' "to_string: " to_string(f) "\n\n"; >
std::cout: 23.43 to_string: 23.430000 std::cout: 1e-09 to_string: 0.000000 std::cout: 1e+40 to_string: 10000000000000000303786028427003666890752.000000 std::cout: 1e-40 to_string: 0.000000 std::cout: 1.23457e+08 to_string: 123456789.000000

Источник

Оцените статью