-2

Write a program that takes its input from a file of numbers of type double. The program outputs to the screen the standard deviation of the numbers in the file. The file contains nothing but numbers of type double separated by blanks and/or line breaks. The standard deviation of a list of numbers x1, x2, x3, and so forth is defined as the square root of:

((x1 – a)2 + (x2 – a)2 + (x3 – a)2 + ...) / (n - 1)

Where the number a is the average of the numbers x1, x2, x3, and so forth and the number n is the count of how many numbers there are.

Your program should take file name as input from the user.

I have already created a file in the computer. When I finish the code and try to compiled it, it cannot open the file in the compiler. I don't know what is the problem going on. Can anyone give me some advices?

#include <stdio.h>
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>

using namespace std;


int main()
{
    double next, avg,var,stdDev, sum=0, sumSq=0;
    int count=0;

    cout << "Enter filename:" << endl;
    std::string filename;
    cin >> filename;

    ifstream in_stream;

in_stream.open(filename.c_str());


   while(in_stream >> next)
   {
       sum+=next;
       sumSq+=(next*next);
       ++count;       
   }

   avg=sum/count;
   var=(count*sumSq-sum*sum) / (count*(count-1));
   stdDev=sqrt(var);

   in_stream.close();

cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout.precision(3);
cout << "The standard deviation is " << stdDev << endl;



return 0;
}



 [1]: http://i.stack.imgur.com/luJZx.png



 [2]: http://i.stack.imgur.com/ofZGR.png


 [3]: http://i.stack.imgur.com/xTFSL.png
ZiWei Pan
  • 13
  • 5
  • Where is the file located? Where is the .exe located? – NathanOliver Jul 15 '16 at 17:50
  • Are you sure that the file resides in your programs working directory? – πάντα ῥεῖ Jul 15 '16 at 17:50
  • Also fix your question title please! It's obviously completely unrelated to your actual problem. Post a [MCVE] that reproduces your problem please, and leave out all that irrelevant stuff. – πάντα ῥεῖ Jul 15 '16 at 17:53
  • 1
    It cannot open the file ? How do you know that. The posted code makes no effort to check *any* of your IO operations. And you may want to read this to see why [`while(! file.eof() )` is wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). If you indeed cannot open the file, my crystal ball tells me its because the *working* directory your process is running from is not the same as that where `nums.txt` resides. – WhozCraig Jul 15 '16 at 17:55
  • Also asking for entering a filename and actually don't put a statement doing this looks pretty silly for me. I don't know who upvoted this poor question for what ever reason?? – πάντα ῥεῖ Jul 15 '16 at 17:59
  • There is so much wrong with what you've done. Be systematic. Try tracing through your code with a debugger and you'll find many deficiencies. – Ian Jul 15 '16 at 20:32
  • @ NathanOliver: my file is located on the Desktop. What do you mean by .exe? I think the file name should be .txt. – ZiWei Pan Jul 15 '16 at 23:55
  • Your program does not allow the user to input a file name. Instead, it hard codes this file name as nums.txt in both getAverage() and standardDeviation(). To allow the user to input the file name add `std::string fileName; std::cin >> fileName;` after the first line in `main()`, after the line with `std::cout ...`, and add `#include `. Then, pass `fileName` to both `getAverage()` and `standardDeviation()` and use them to open the file (i.e., `file.open(fileName.c_str())`). Note that is this just a start. There are still so much that is bad/inefficient with your code. – aichao Jul 16 '16 at 03:06
  • @aichao: I try to rewrite my code. But I stop after the average part, because I am not sure how to write the standard Deviation part. – ZiWei Pan Jul 16 '16 at 19:14
  • @ZiWeiPan: the key is to sum the square of `next` while summing `next` as `sum`. Call that `sumSq`. Then the unbiased sample variance is `(count*sumSq - sum*sum)/(count*(count - 1))`. The unbiased sample standard deviation is just the square root of that. BTW, your posted code still has problems. One of which is that you are missing a `)`. – aichao Jul 17 '16 at 03:39
  • @aichao: Is it sumSq=sqrt(sum+next)? for the standard deviation part, do I need another while statement like the previous one? – ZiWei Pan Jul 17 '16 at 05:07

1 Answers1

0

This is what you need

#include <iostream>
#include <cmath>
#include <fstream>
#include <string>

using namespace std;

int main() {
  double next, avg, var, stdDev, sum=0, sumSq=0;
  int count=0;

  cout << "Enter filename: ";
  std::string filename;
  cin >> filename;

  ifstream in_stream;
  in_stream.open(filename.c_str());
  if(in_stream.fail()) {
    cout << "Could not open the file " << endl;
    exit(0);
  }

  while(in_stream >> next) {
    sum += next;
    // sum the square of "next"
    sumSq += (next * next);
    ++count;
  }

  avg = sum/count;
  var = (count*sumSq - sum*sum)/(count*(count - 1));
  stdDev = sqrt(var);

  cout << "The mean is: " << avg << endl;
  cout << "The unbiased sample variance is: " << var << endl;
  cout << "The unbiased sample standard deviation is: " << stdDev << endl;

  return 0;
}

Compile this and execute the executable from the SAME directory as your nums.txt file. Then after the program prompts you with Enter filename:, enter nums.txt. For example, a screen grab of my session in a terminal is:

enter image description here

I used g++ but you can use clang++ as well to compile.

Hope this helps.

aichao
  • 6,680
  • 3
  • 11
  • 16
  • Thanks! This one helps me a lot. After I rewrite my code, when I input the filename, the output is "The standard deviation is nan." Not a specific number, actually I put some numbers into my file. Do you know what is the problem of this? – ZiWei Pan Jul 17 '16 at 17:41
  • @ZiWeiPan: can you post the input file? How many white-space separated numbers are in the file? – aichao Jul 17 '16 at 17:49
  • I don't know how to insert a file. Can I post it like an image? – ZiWei Pan Jul 17 '16 at 18:02
  • You can. What operating system are you using? – aichao Jul 17 '16 at 18:04
  • @ZiWeiPan: make sure your input file contains only numbers (can have decimal and sign) that can be converted to double. Otherwise, you will get `nan`. I did not get a `nan` with the data in your screen grab. – aichao Jul 17 '16 at 18:29
  • My input file just have numbers (no decimal and sign). May be there are some errors on my code. Can you take a look for my code? – ZiWei Pan Jul 17 '16 at 18:34
  • You need to change your posted code in the question to be the code in the answer. Your posted code in the question will not even compile correctly. If you do that and follow the commands in the session screen grab that I just posted, then all will be well. – aichao Jul 17 '16 at 18:44
  • I have already updated my code. This one is the complete code. – ZiWei Pan Jul 17 '16 at 19:44
  • Compiling using `clang++ -o std_dev std_dev2.cpp` and running your posted code, I get `The standard deviation is 33.982` as the output for your `nums.txt` file. So, there is nothing wrong with your code now. Like I said, if mums.txt has any non-numeric lines in it, then you will get `nan`. – aichao Jul 17 '16 at 19:56
  • I double checked my code and my file. There is no error in the code also no numeric lines in the file, but I just keep getting "nan" when I compile the program. – ZiWei Pan Jul 17 '16 at 20:03
  • @ZiWeiPan: take a look at my session screen grab that I just updated. When you `cat` your nums.txt file, do you get the same output as that shown in the screen grab? – aichao Jul 17 '16 at 20:07
  • No. I post an image during my compiling. – ZiWei Pan Jul 17 '16 at 20:23
  • @ZiWeiPan: please issue the command `cat nums.txt` in the terminal and show me the screen output. – aichao Jul 17 '16 at 20:28
  • I tried as you said, but I get the same result. I also post the image. – ZiWei Pan Jul 17 '16 at 20:45
  • Ok! I know what is the problem because I do not put the file in the right path. – ZiWei Pan Jul 17 '16 at 20:49
  • @ZiWeiPan: the `cat nums.txt` command should be run from the terminal prompt and **not** as the input to your program. Just run `cat nums.txt` from the terminal and post that screen shot. Don't run `./a.out`. – aichao Jul 17 '16 at 20:49
  • @ZiWeiPan: Yes, you should check to see if the stream opened correctly. You had that before and you removed that from your code! See the code posted in the answer. You are getting `nan` in this case because `count` is zero. – aichao Jul 17 '16 at 20:52