Conversion from double to string in c++ [duplicate] - c++

This question already has answers here:
Turn off scientific notation on float
(2 answers)
Closed 2 years ago.
I'm currently coding a project for my Computer Science module but I'm having the problem of my string value defaulting to scientific notation if there are too many decimal places in the double value.
I've tried the obvious solution with ostringstream and .str() but it makes it into notation. I have to compile to the C++98 standard, so I cannot use modern solutions like std::to_string.
I need the value to be casted into a string but it needs to maintain its formatting. any help would be appreciated.

I would use:
std::to_string(myDouble);

If you use at least C++17, you could use std::to_chars() from #include <charconv>.
// `512` is here arbitrary, it is the max size of the output string.
// Smaller values should be sufficient.
char buffer[512];
// Here 'std::chars_format::fixed' tells the `std::to_chars()` to
// not use the scientific notation.
char* end = std::to_chars(std::begin(buffer), std::end(buffer), myDouble, std::chars_format::fixed).ptr;
// `end` the one-past-the-end pointer of the characters written to `buffer`.
This method is probably faster than the Emilien Lemaire's answer, however it's more verbose, and more error-prone. So this answer is only provided for completeness (as the performance gain may not worth it).
Moreover, unlike std::to_string(), the output string is locale-insensitive, so the double will always be formatted in the C locale (english locale).

Related

Is there a way to multiply a string and an integer in C++? [duplicate]

This question already has answers here:
Multiplying a string by an int in C++
(10 answers)
Closed 2 years ago.
In Python, there is a way to multiply a string, for example, "A" * 3 would return "AAA". However, this syntax doesn't work in C++, it just gives me an error, invalid operands of types 'const char [2]' and 'int' to binary 'operator*'. Is there a way to multiply a string like this in C++?
There is no such operator in C++.
But you can write a function that takes a string and a number as argument, and return the repeated string.
std::string also has a constructor that repeats given character a number of times. This may be useful since you used a string of one character as the example.
You can overload an operator
std::string operator*(const std::string& s, unsigned n)
{
... // your code here
}
Not really... Although you can right one yourself. C++ is a very different beast to Python. It's much more low level and It is not as forgiving.
C++ deals with "real" memory (as it were).
You can't really just say "A" * 3 because before the "A" simply used 1 byte of memory if you have 3 "A"'s you need 3 bytes. and since C++'s main benefit is in it's ability to allow the user to author It's memory use, C++ won't just create 3 extra bytes.
You can implement your own version of Python's "A" * 3 by using the overload operator (although you would have to use a class type like string) C++ provides But I wouldn't really recommend this.
I'd suggest just using a std::vector and append the character as many times as you would like.
Also have a think about what you are trying to really do. C++ is all about performance rather than usability. If you are trying to set multiple bytes to a certain value you can use std::memset

How to convert a double into a char* [duplicate]

This question already has answers here:
Converting double to char* in C++ with high performance
(9 answers)
Closed 7 years ago.
I am heavily struggling with a question which should be very easy: how do I do a simple type conversion (from double into char*) in basic C.
I have found quite some solutions, but they are all based on conversions from double to char[x], but I am working here with char*, not with char[]. (I don't know how long the resulting string will be).
On top of that, I really can't believe that another type (be it stringstream, std::strings, ...) are needed for something that simple.
I admit, I'm a complete newbie in basic C, but I have worked in other languages (Visual Basic, Delphi, Java, ...) and I just can't understand why I can't find a simple function like "to_char_pointer(double d)" to do this.
Does anybody have an idea?
You can use sprintf() as you have done to convert a double to a string, but I would actually recommend using _snprintf() instead simply because sprintf() has no regard for the fact that strings are fixed length devices in memory and will overflow if you don't watch it. _snprintf() allows you to specify the length of the out string, just be sure to specify the size as one less than the actual allocated memory block, because _snprintf() does not store the terminating null character if it has to cut the output short.
An example us using _snprintf() is:
void ToString(char * outStr, int length, double val)
{
_snprintf(outStr,length,"%f",val);
}

c++, converting input string to number, failure to convert should not return zero [duplicate]

This question already has answers here:
Is there a TryParse equivalent in C++ (gcc)?
(4 answers)
Closed 7 years ago.
Hi im looking at the string conversion methods in c++ strtol, strtoll, strtoul, atol etc.
It seems every single one of them will return a 0 (or 0.0) as a result for a string that was impossible to convert.
Assuming that 0 is a completely valid correct input for my program how do I avoid converting nonsense strings to zero and make for example them throw some exception instead? Are there ready made functions that perform that way or do I have to wrap these with some of my own code.
Also could anybody explain me what might the reasons be that these functions are designed like this (Why build in the trouble of separating nonsense string parse result from hones-to-god "0" string parse results)?
Failure is indicated by setting errno, which is the old-fashioned C way of doing things.
You might find stol and friends more useful - they indicate failure by throwing an exception.
http://en.cppreference.com/w/cpp/string/basic_string/stol
You can use the std::stoi() std::stof() function family to do this. The functions will throw an exception for invalid input.
You may find useful boost/lexical_cast.

Input of integer in the range of 10^1000 [duplicate]

This question already has answers here:
Handling large numbers in C++?
(10 answers)
Closed 8 years ago.
Is it possible to take an input of range greater than what C/C++ provides? Is it possible to accept an input range greater than that of unsigned long long and even larger up to the range of 10^1000?
If it is possible in C/C++, please answer how it can be done, thanks.
There's no bigint in C or C++, however library like this one can provide it: https://code.google.com/p/infint/
Input into a string. Then convert the string into the desired type.
If you use a library that provides types for large integers, such a library might also offer input functions.

Format a String in C++ with the same convenience as String.format() in Java 5 / 6? [duplicate]

This question already has answers here:
How to construct a std::string with embedded values, i.e. "string interpolation"?
(8 answers)
Closed 2 years ago.
Is there a common function available to be able to do sprintf type String formatting without having to supply a fixed size buffer, that returns a string class instance?
I know about stringstream it doesn't do what I want, I don't want to hard code the position of the tokens in the output statement like it requires.
I want to be able to define a pattern like sprintf lets you, but without the C baggage and in a more idiomatic Object Oriented C++ manner.
Maybe some function that does what sprintf does using a stringstream and produces a string object? Something along the line of the convenience of what String.format() does in Java or the equivalent String formatting syntax in Python.
The Boost Format Library:
The <boost/format.hpp> format class provides printf-like formatting, in a type-safe manner which allows output of user-defined types.
If you don't use Boost.Format or Boost.Locale you can use my simple stringstream wrapper or wrap it even further:
fakeformat
example:
REQUIRE( ff::format("{2}ff{1}").with('a').also_with(7).now()=="7ffa" );
Ideone