Search code examples
c++ostream

How do I return 8.0 instead of 8 when using streams?


The formatting and output of this code matches the sample output of my assignment, but the issue is that I am returning 8 when I want it to be 8.0.

What should I do?

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

void runningSum(istream &in, ostream &out)
{
    string line, str;
    double sum = 0, max = 0;
    while (getline(in, line))
    {
        istringstream sin(line);
        out << "running sum = ";
        while (sin >> str)
        {
            sum = sum + stod(str);
            out << sum << " ";

            if(max < sum) max = sum;
        }
        out << "\nmax sum = " << max << endl;
    }
}

int main()
{
    ifstream in("in.txt");
    runningSum(in, cout);
    return 0;
}
// in.txt: 3.25 4.5 -8.25 7.25 3.5 4.25 -6.5 5.25
// my output:
// running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8 13.25
// max sum = 14.5
// desired output:
// running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8.0 13.25
// max sum = 14.5

Solution

  • Your code is fairly sensible, the requirement is just slightly tricky.

    What I suggest is to write a function to format doubles in the desired form, adding a trailing ".0" if necessary

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <sstream>
    #include <iomanip>
    #include <cmath>
    
    std::string format(double value)
    {
        std::stringstream ss;
        ss << value;
        // check for existing decimal point
        if (ss.str().find('.') == std::string::npos)
        {
            ss << ".0";
        }
        return ss.str();
    }
    
    void runningSum(istream &in, ostream &out)
    {
        for (std::string line; getline(in, line);)
        {
            double sum = 0;
            double max = std::numeric_limits<double>::lowest(); // could be always negative
            std::istringstream sin(line);
            out << "running sum = ";
            for (double value; sin >> value;)
            {
                sum += value;
                out << format(sum) << " ";
    
                max = std::max(max, sum);
            }
            out << "\nmax sum = " << format(max) << "\n";
        }
    }
    
    int main()
    {
        std::ifstream in("in.txt");
        runningSum(in, std::cout);
        return 0;
    }