Adding Arguments to my program

Hello everyone I am new to c++ programming and I wrote a program in VS 2015 that asks the user for a file name and if it exists it reads the the floating point numbers and outputs the average of the numbers. I am need to make changes to the program are if the user doesn’t specify any file name, then prompt the user for the name. I know I needed to include (int argc, char* argv[]) but I have no clue what to do next. This is an online class and having trouble getting response from my profession. Any help would be greatly appreciated.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main(int argc, char* argv[])

{

//First, prompt the user to enter the name of a file to read from.Use
cin to read the file name, then send it to the fstream to open the
file.

string filename;

cout << "Enter name of file: ";

cin >> filename;

fstream file;

file.open(filename);

//Count the number of values read in, in addition to adding all of
the numbers up.

float sum = 0;

int count = 0;

float temp;

//Use a while loop with the condition set as
inputting file >> temp to read the current number.
The loop ends when the file does not read a floating point anymore.

while (file >> temp)

{

sum += temp;

count++;

}

//Take the sum of all of the numbers and divide it by the number of
values read to obtain the average.

float average = 0;

if (count != 0)

{

average = sum / count;

}

cout << average << endl;

}
1
2
3
4
if (argc>1)
   filename = argv[1];
else
   std::cin>>filename;

If you want tab-completion, may use readline http://linux.die.net/man/3/readline
Last edited on
Where would I put this code?
At the point where you want to check whether a filename has been specified, and prompt the user if it hasn't.
Topic archived. No new replies allowed.