Hello, I have written a program that I need a user to put in as many double values as they want, and then it saves those values to a file. I am stuck with what I have, the program gets the values but wont execute. What is wrong with the code?
#include <iostream>
#include <fstream>
#include <iomanip>
# include <string>
using namespace std;
int main ()
{
string end;
double UserInput = 0;
while(UserInput != 'end')
{
cin >> UserInput;
}
while(UserInput == 'end')
{
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << UserInput << endl;
myfile.close();
}
else cout << "Unable to open file";
}
cout << endl;
system("pause");
return 0;
Just a few things that come to mind.. What were you planning to do with the string end? You declare it but do nothing with it. Also, the first loop is going to be infinite because UserInput is a double, not a string like you check it against (which should be in double quotes by the way). Maybe you could have a terminating value, like -1 or something. Better yet, since it's a double which usually shouldn't be compared with a '==', you could tell the user to input anything less than -100000, or any number you want. Next, if the first loop ever meets a terminating condition, the second one would be infinite, since the value of UserInput is never changed. You shouldget rid of the second while loop, put all the contents into the first loop, not close the file, and move the ofstream statement to the beginning of main().
That's because you only have one variable for storing numbers.
double UserInput = 0; Creates a single variable called UserInput
cin >> UserInput; Writes the entered value into the variable UserInput
You only have one variable, and you always put the entered value into that variable (which will overwrite the previous value stored there).
You either need to store all the variables the user enters (perhaps in some kind of array, or since this is C++ maybe in a proper grown-up container like a vector), or write each entered value to file as they come in, so that it doesn't matter that you keep no record of them.