how to pass command line parameters to functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <stdlib.h>
using namespace std;
     
class empsalary
{
int salary;
public:
void display(int r)
{
salary=5000;
salary=salary+r;
cout<<salary<<endl;
  }
};
int main(int argc, char* argv[])
{
char str[]=argv[];
int result=atoi(str);
empsalary e;
e.display(result);
return 0;
 }


i am trying to pass a parameter result to display method by taking the input from command prompt but its not working.
Last edited on
char str[]=argv[]; How do you expect that to work? str is an array of chars and argv is an array of char pointers. When you're declaring an array, you must know it's size beforehand. The only time when you write char str[] = ... is when you immediately initialize with {'a', 'b', ...} or "ab...". If you wanted to put the contents of the first argument into an array of your own, you'd write
1
2
char str[11];//assuming the input won't be more then 10 chars long
strcpy(str, argv[0]);

But there is really no reason to do that at all. Why not just atoi(argv[0])?
like this ? its not working am i doing anything wrong ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stdlib.h>
using namespace std;

class empsalary
{
int salary;
public:
void display(int r)
{
salary=5000;
salary=salary+r;
cout<<salary<<endl;
  }
};
int main(int argc, char* argv[])
{
int result;
char str[] =atoi(argv[0]
result=str[];
empsalary e;
e.display(result);
return 0;
 }

Ask yourself what does atoi return and what is the type of str. Does it make sense to assign them to one another? Ask the same for str and result.
Also, you're missing a ");" after argv[0]. I'm sure the compiler is giving you very clear messages about what is wrong. Just read them.
Also, you're missing a ");" after argv[0]. I'm sure the compiler is giving you very clear messages about what is wrong. Just read them.

thx for the reply, atio extracts integer values from chars so i changed the code a bit and instead of assigning atoi(argv[0]) to a character type (str) i assigned it to integer and passed it to display,its working now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <stdlib.h>
using namespace std;

class empsalary
{
int salary;
public:
void display(int r)
{
salary=5000;
salary=salary+r;
cout<<salary<<endl;
  }
};
int main(int argc, char* argv[])
{
empsalary e;
int result;
result=atoi(argv[1]);
e.display(result);
return 0;
 }


Topic archived. No new replies allowed.