A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/cpp_standard_library/cpp_string_stold.htm below:

C++ String to Long Double Conversion

C++ String::stold() function

The C++ std::string::stold() function is used to convert a string into a long double value. It analyse the string from its beginning up to the first character that is not part of the number. If the conversion is successful, It returns the result as a long double.

If the string conversion gets failed, it throws a invalid_argument exception.

Syntax

Following is the syntax for std::string::stold() function.

long double stold (const string&  str, size_t* idx = 0);
long double stold (const wstring& str, size_t* idx = 0);
Parameters Return value

This function returns the double type representing the converted value of the string.

Example 1

Following is the basic example to convert a string into double of std::stold() function using C++.

#include <iostream>
#include <string>
using namespace std;
int main() {
   string number = "123.456";
   double value = stold(number);
   cout << "The double value = " << value << endl;
   return 0;
}
Output

If we run the above code it will generate the following output.

The double value = 123.456
Example 2

Following is an another example of std::stold() function used to exctract a double value from a string that contains both text and numbers.

#include <iostream>
#include <string>
using namespace std;
int main() {
   string mixedString = "Total: 250.75 USD";
   size_t pos;
   double amount = stold(mixedString.substr(7), & pos);
   cout << "Amount = " << amount << endl;
   return 0;
}
Output

If we run the above code it will generate the following output.

Amount = 250.75
Example 3

In this example, we have given a invalid input, so it will throw an invalid_argument exception because the string cannot be converted to double.

#include <iostream>
#include <string>
using namespace std;
int main() {
   string invalidNumber = "abc";
   try {
      double value = std::stold(invalidNumber);
      cout << "Value is: " << value << std::endl;
   } catch (const invalid_argument & e) {
      cout << "Invalid argument: " << e.what() << endl;
   }
   return 0;
}
Output

Following is the output of the above code.

Invalid argument: stold          

string.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4