Hello everybody. I am a student who is taking a C++ class and I am doing an assignment that I dont know is correct. Our teacher says that even if you get the right answer that doesn't mean your code is correct. SO my project is to get a file from a designated location in my computer and not just read, but grab the values from the user and make a count, sum, and average calculation of the numbers in my code. I am using the fstream library and I am trying I did do it, I got the values and calcualated them, however I want the values to be accessed from maybe my desktop or my drive, I want to know how to manipulate my code to get a path like C:\\User\Desktop and maybe executed from the path input or given. I dont know if this is possible, or easy to do. ALso I did copy some of this code from my teachers examples and I dont know exatly why the variables have to be initilized at zero, and I would like to know a little more on the Bitwise right shift breaker used in line 20 something. Well If anyone could help, this would be greatly appreciated.
Here is my code below.
#include <iostream>//For avergae functionality
#include <fstream>//For the file commands, such as ifstream and the Bitwise right breakers(<< and >>).
#include <iomanip> // To control the amount of decimals in my results desired.
int main ()
int aNumber=0; //Initilized at zero because of Stack Overflow:
cout << "failed to read file.";
while (randomFile >> aNumber)
average = sum/numbers;
cout << "Number of numbers: " << numbers << "\n";
cout << "Sum of the numbers: " <<fixed<<setprecision(2)<<sum << "\n";
cout << "Average of the numbers: " <<fixed<<setprecision(2)<< average<<"\n \n \n";
Again thax a lot for the help I have gotten from the past from some of you.
You see how the open() function takes a string as input? That string doesn't have to be constant. You can ask the user to input a path via std::cin and use that as the argument to open().
When an istream (like std::cin or an ifstream) is cast to a boolean, it returns whether its state is still "good" (the good state includes or not it found an end-of-file). The overloaded >> operator returns the istream to the left each time it's used, which is what lets you chain together istream >> var statements.
That's what allows the while loop to work. It keeps going until the ifstream hits an end-of-file, at which point it stops being "good".
Thank you, for your explanation Albartross. But I dont get why you say the string does not have to be a constant. I probably have not grasped the true definition constant in proramming. Also I would like to know why to initilize the values at 0 Like int aNumber = 0 and the other variable numbers = 0. I am sorry I am being so picky, but I did get the "good" and bad loop concept, when the while loop is still valid, meaning the file searched or just the command was True the code is good, when not true, (.false) loop not good. Tanx again for your effort.