Program Help!

Hi, I've been having trouble with a program where I have to name my own text file then input a string of numbers. In the second step I must process the existing file and extract the numbers then add them all up, find the average of the sum, and ultimately output the average.

Here is what I have at the moment:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
int selection, number = 0;
string fileName;
ofstream test;
cout << "Welcome to the number cruncher program would you like to" << endl;

do {
cout << "1) Enter numbers to a new file" << endl;
cout << "2) Process numbers from an already existing file" << endl;
cout << "Please enter your number selection" << endl;
cin >> selection;
} while (selection != 1 && selection != 2);

if (selection == 1)
{
cout << "Please enter a file name that your numbers will be saved to: " << endl;
cin >> fileName;
test.open(fileName);
do
{
cout << "Please enter a positive number or enter a negative number to quit" << endl;
cin >> number;
if (number > 0)
test << number << " ";
} while (number >= 0);
test.close();
}

if (selection == 2)
{
double average = 0;

cout << "Please state the file you would like to access:" << endl;
getline(cin, fileName);\\Here is where I'm having
cin.ignore(); \\trouble with extracting
ifstream release; \\averaging and outputting.
string console;
string line;
release.open(fileName);
if (release)
{
while (release >> line)
{
console += line + "\n";

}
}

else
cout << "Error opening file." << endl;
cout << console << endl;
release.close();
}

system("Pause");
return 0;
}

Any and all advice is appreciated! Thank you for your time.
closed account (2UD8vCM9)
The reason you're not able to open the file, is because you aren't actually getting the file name like you think you are.

You need to call cin.ignore(1000,'\n'); before you call getline after you cin>> anything.

So it should look like

1
2
3
cout << "Please state the file you would like to access:" << endl;
cin.ignore(1000, '\n');
getline(cin, fileName); 


That being said, when you are reading the contents why are you reading them into a string? Where you have while (release >> line) why are you not reading it into a double or float instead so you can actually add it to the sum to average?
Cool, thanks for the help! It worked out very well.
Topic archived. No new replies allowed.