c++iostreamsstream

How to assign results from std:fixed << setprecision(5) to variable in c++


Couldn't find an answer for following question:

I'm new to C++ and am doing some tests now. I'm using std::fixed and std::setprecision functions to get a decimal number with 5 zeros. This works using cout, but i have no idea how to assigning the results to a variable instead of printing them using cout.

//Works
int fetchJD(std::string str) {
    std::cout << std::fixed << std::setprecision(0) << str;
    return 0;
}

I tried things like using sstream but whenever i try to assign the results to another string so i can return the results, lets the compiler fails.

// Not working  
int fetchJD(std::string str)
{
    std::stringstream ss;
    string temp;
    ss << std::fixed << std::setprecision(0) << str;
    temp = ss.str();

    return temp;
}

Which results in the compiler as error:

In function ‘int fetchJD(std::__cxx11::string)’:
astroapp.cpp:43:12: error: cannot convert ‘std::__cxx11::string {aka 
std::__cxx11::basic_string<char>}’ to ‘int’ in return
return temp;

So how can i pass the results from std::fixed << std::setprecision(0) << str; into another string?


Solution

  • You still need to convert the result back to an int (but that will never change the way the integer is displayed).

    return std::stoi(ss.str());
    

    This gives you an int, a simple int, no precision, nothing. All the processing of changing the precision and the fixed won't change anything, as you have a string at the beginning, which is not changed by these modifiers.

    So basically you are not doing anything with your function.

    If you want to convert a string to a value, use stoi, stod...