hello , real problem

my teacher want to write code in argument like this

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std ;
int main (int argc , char* argv[])

{
int x=0 , y=0;
x=argv[1][0] - '0';
y=argv[2][0] - '0';
cout << "sum = "<< x+y <<endl;
return 0 ;
}


then g++ myfil.cpp -o my
./ 123 5

now i have aproblem because the program just read one digit .
please i need an answer ...

thanks
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstdlib>
using namespace std ;
int main (int argc , char* argv[])

{
int x=0 , y=0;
x=atoi(argv[1]);
y=atoi(argv[2]);
cout << "sum = "<< x+y <<endl;
return 0 ;
}

atoi = http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
You should check if argc >= 3.
how can i check argc ,

is atoi do it alone ?
how can i check argc ,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdlib>
using namespace std ;
int main (int argc , char* argv[])

{


if(argc != 3) {
cerr << "we need exactly two numeric arguments!" << endl;
return -1;
}

int x=0 , y=0;
x=atoi(argv[1]);
y=atoi(argv[2]);
cout << "sum = "<< x+y <<endl;
return 0 ;
}

something like that...

is atoi do it alone

atoi is a function in the c/c++ standard library. this function converts a numerical string into an integer, so you are able to do numerical operations with it.
shadow ,

did you understand my question ?

i am coding in c++ under linux by arguments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    
    int , x=0 , y=0 ,z=0;
    x=argv[1][0]-'0';
    y=argv[2][0]-'0';
            cout<<" sum =  "<<x+y<<endl;
    
    return 0;
}


for example the file name k.cpp

i do this

g++ k.cpp -o k
./k 4 5

the output will be 9 ,

but if i write like this

./k 122 5

will be an error ,

" i need if i write this ./k 122 5 the output will be 127 " -> that is the problem .

thanks
He answered you. That's a good answer, even.
They are both right: You are going to need atoi to get any number with more than one character in it using the argument vectors the way you are.
Topic archived. No new replies allowed.