String to Long Number Back To String

Hello! I was just asked a question that I need some help with.

The question was given two strings that are numbers. Then add the numbers together (find the sum). Then to convert the answer back to a string.

The catch is I was asked to do this without casting.

I know how to solve the problem with casting. But I have no idea how to go about doing it without. I've tried browsing around and haven't come up with anything.

Does anyone know how to go about doing this?

1
2
3
4
5
6
7
8
9
10
    string string1 = "3.14";
    string string2 = "0.9";

    long double anw = 0.0;

    string anwser;
    anw = stold(string1) + stold(string2);
    anwser = to_string(anw);

    cout << anwser << endl;
There are numeric conversion functions in <string>, use the one that will convert your two strings to doubles.
https://en.cppreference.com/w/cpp/string/basic_string/stof

(example how to use by converting a string to int):
https://en.cppreference.com/w/cpp/string/basic_string/stol

Add the numbers together and then convert back to string using std::to_string:
https://en.cppreference.com/w/cpp/string/basic_string/to_string
Last edited on
You can also use stringstreams to those conversions.

Yeah, converting via stringstream is probably a more modern way to convert to a numeric value.
@Furry Guy, so the way I have it done would be the best way to go about it?

@jlb, if it isn't to much trouble could you give me a quick example of how? I'm looking at:

https://www.cplusplus.com/reference/sstream/stringstream/

but don't really see how I would apply that.
Start by looking at the operator>> and operator<<.

An example of using std::stringstream to convert a number to a string, and a string to a number.
https://en.cppreference.com/w/cpp/io/basic_stringstream/basic_stringstream

I keep forgetting about using stringstream for conversion from/to numeric values. The <string> functions are nice, but <sstream> is IMO better suited for simple conversions. Using stream I/O is consistent no matter what the source or destination.

If you can read a numeric value from std::cin, you can read a value from file or a stringstream in the same manner. The same with outputting a value.
it may be faster and simpler to do this yourself in a little loop that adds the numbers as strings.
that may not work if you have a school assignment to do it their way, but it seems like it would save a lot of complexity -- you just iterate backwards over the strings, carry and add... ?
I have it done would be the best way to go about it?


That's a good way to do it - but depending upon other factors would depend upon whether it is the best way. eg, do you need to know where the end of the converted string is? What if the string to be converted isn't a number, is performance a factor (use from_chars() [for VS2019]) etc etc.
Topic archived. No new replies allowed.