command-line argument error

Write your question here.
My code is giving me the error "a function definition is not allowed here before the '{' token. I'm thinking it is because of the arguments I pass in the main function but I thought its supposed to work. Any help?

#include<iostream>
#include<cstdlib>
#include<cmath>
#include<iomanip>
using namespace std;

void displayauto(double arr1[], double k, int N0)
{
cout << "Bacteria Initialized:" << '\n';
cout << " Growth factor (k) = " << k << '\n';
cout << " Initial population (N0) = " << N0 << '\n' << '\n';
int t = 0;
cout << " Growth Summary:" << '\n' << '\n';
cout << " Hour Population" << '\n';
cout << " ==== ==========" << '\n';
while(t<11)
{
cout << " " << t << " " << setprecision(3) << fixed << arr1[t] << '\n';
t++;
}
}

void initialize(double& k, int& N0)
{
cout << "Initializing Bacteria:" << '\n';
cout << " Growth factor (k) [0.0-1.0] :";
cin >> k;
cout << " Initial population (N0) [1-1000] :";
cin >> N0;
cout << '\n';
}

void calculate(double arr[], double k, int N0){
for(int t = 0; t<11; t++)
arr[t] = N0*(exp(k*t));

}

void display(double arr1[])
{
int t = 0;
cout << " Growth Summary:" << '\n' << '\n';
cout << " Hour Population" << '\n';
cout << " ==== ==========" << '\n';
while(t<11)
{
cout << " " << t << " " << setprecision(3) << fixed << arr1[t] << '\n';
t++;
}


int main( int argc, char* argv[]){
int N0;
double k;
double array[11] = {0,0,0,0,0,0,0,0,0,0,0};
if(argc <= 1){
initialize(k,N0);
calculate(array,k,N0);
display(array);
}
else{
k = argv[1];
N0 = argv[2];
calculate(array,k,N0);
displayauto(array,k,N0);
}
return(0);
}
Last edited on
Please use code tags. http://www.cplusplus.com/articles/jEywvCM9/

You forgot a curly brace.
1
2
3
4
5
6
7
8
9
10
11
12
void display( double arr1[] ) 
{
    int t = 0;
    cout << "   Growth Summary:" << '\n' << '\n';
    cout << "   Hour    Population" << '\n';
    cout << "   ====    ==========" << '\n';

    while( t < 11 ) {
        cout << "   " << t << " " << setprecision(3) << fixed << arr1[t] << '\n';
        t++;
    }
}


1
2
int N0;
double k;

Make sure to initialise variables.

double array[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
can be shortened to
double array[11] = { 0 };

1
2
        k = argv[1];
        N0 = argv[2];

You're implicitly converting a C-string to a number, which is probably not what you intend to do. Look at http://www.cplusplus.com/reference/cstdlib/atoi/ and http://www.cplusplus.com/reference/cstdlib/atof/ .
Alternatively, you could use stringstream like so:
1
2
3
4
5
6
7
8
    const char str[]{ "1337" };
    
    std::stringstream ss;
    ss << str;
    int num{ 0 };
    ss >> num;
    
    std::cout << num << "\n";


1337
Last edited on
sigh thanks mate
Topic archived. No new replies allowed.