I need to write a program that finds the sum, product, or mean of a set of numbers using the command line. I'm thinking this should work but now it says cout is ambiguous. what am I doing wrong?
You are thinking the wrong way about how the program is taking input. Trash your thought process of using the arguments in main. Start over I will give you one example that you can use to help you to finish your project.
#include <iostream>
usingnamespace std;
int main()
{
int x, y, sum;
cout << "Enter first value to be added. " << endl;
cin >> x;
cout << "Enter second value to be added. " << endl;
cin >> y;
sum = x + y;
// for division use sum = x/y;
// for subtraction use sum = x-y;
// for multiplication use sum = x*y;
// ***of course you want to change the sum name to fit exactly what
// you are doing like if you are subtracting, a more appropriate name would
// be difference. For multiplication product.
cout << "The sum of " << x << " + " << y << " = " << sum << endl;
system("PAUSE");
return 0;
}
That hint doesn't tell you to make that the very first thing in the main function. Before you use that, you need to check that you actually have two or more arguments.
#include<iostream>
#include<string>
#include<cmath>
#include<iomanip>
usingnamespace std;
int main(int argc, char** argv)
{
float sum = 0;
float product;
float mean;
int index = 2;
// Calculate sum and product as long as the user enters numbers.
while(index <= argc)
{
float number = atof(argv[index]);
sum += number;
product *= number;
index ++;
}
//Return 1 from main and do not print anything because the program is called without any arguments
if (argc < 2)
{
return 1;
}
string option = string(argv[1]);
if(option != "sum" && option != "product" && option != "mean")
{ //Return 1 from main and do not print anything because the first argument does not match any of the three expected strings
return 1;
}
//Return 1 from main and do not print anything because no numbers are provided
elseif(argc<3)
{
return 1;
}
//User selected sum option. Print the sum of the numbers entered by the user.
elseif(option == "sum")
{
cout<<sum;
return 0;
}
//User selected product option. Print the product of the numbers entered by the user.
elseif(option == "product")
{
cout<<product;
return 0;
}
//User selected mean option. Print the mean of the numbers entered by the user.
elseif(option == "mean")
{
float mean = sum/(argc-2);
cout<<mean;
return 0;
}
}
Hey this is interesting...Is this really a beginner thing? I have never seen the
utilization of variables from the main function..except for win32 programming.
Where can I learn more about this technique?