0

I would like to take the sum of all the iterations of getline() and output it to the file I'm reading. However, this current idea of code I have makes the program crash.

int main()
{
    // usual read file stuff
    while (!in.eof())                   
    {

        string total;
        double balance = stod(total);
        getline(in, total);
        cout << "$";
        cout << right << setw(10) << total << '.' << cout.precision(2) << endl;
        //guessing a for loop that would += balance
}
  • 2
    Please read [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) Also please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and learn how to create a [Minimal, ***Complete***, and Verifiable Example](http://stackoverflow.com/help/mcve). You should probably also read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert, and learn how to use a debugger. – Some programmer dude Aug 16 '17 at 05:40
  • By the way, when the string `total` is empty (like it is when you define it) what value do you think `std::stod` would return for it? – Some programmer dude Aug 16 '17 at 05:42
  • 1
    Ah that helps a bit, I thought everytime it ran getline() it would fill balance with it. First time using getline(), does this mean it's even possible to sum from getline? – Dance Zombie Aug 16 '17 at 05:44
  • 1
    Order matters! Statements are executed in the order you write them, from top to bottom. – Some programmer dude Aug 16 '17 at 05:45

2 Answers2

2

The problem lies in

string total;
double balance = stod(total);

After declaring a string, you have no idea what the std::stod is about to return

fix:

string total;
getline(in, total);
double balance = stod(total);
Danyal Imran
  • 1,862
  • 7
  • 17
1

You are trying to convert total to double when it has null value and a null String can not be converted to any data type. That,s why it is generating exception. You will have to convert total to double after assigning a String to it. Just read the total before using stod() function.

Ghulam Moinul Quadir
  • 1,448
  • 1
  • 9
  • 16