0

This is my first program on C++. I successfully build it. When I run it, Windows keep giving me program is stop working, the same result that I try to run it with eclipse.

Here is my code:

#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <vector>

using namespace std;

int main(){

    string input;
    vector<double> value;
    int count = 0;

    while(input != "#") {

        cout << "Enter value " << count + 1 << "\n";
        cin >> input;
        cout << input;
        if (input != "#") {
            value[count] = atof(input.c_str());
        }
        count++;
    }

    cout << count;
    double sum = 0;

    for (int i = 0; i < count; i++) {

        sum += value[i];
    }

    double ave = sum/count;
    double dev = 0;

    for (int i = 0; i < count; i++) {

        dev += pow((value[i] - ave), 2);
    }

    dev = sqrt(dev / (count - 1));

    cout << "\nThe average is " << ave << "\n";
    cout << "The standard deviation is" << dev << "\n";

    return 0;
}

Anyone has any idea? Thank you.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Serena Qi
  • 121
  • 1
  • 3
  • 11

2 Answers2

1
value[count] = atof(input.c_str());

is a problem since value does not have enough space in it. Use

value.push_back(atof(input.c_str()));

instead.

You also have a logic error in the while loop. count will be incremented even when the input is "#". I recommend changing it to:

while(true) {
   cout << "Enter value " << count + 1 << "\n";
   cin >> input;
   cout << input;
   if (input == "#") {
      break;
   }
   value.push_back(atof(input.c_str()));
}
count = value.size();
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

I tried the code on other's computer. It works great. I think something goes wrong for my compiler.

Serena Qi
  • 121
  • 1
  • 3
  • 11