hello , real problem
May 9, 2012 at 6:25am UTC
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
May 9, 2012 at 8:01am UTC
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.
May 9, 2012 at 1:33pm UTC
how can i check argc ,
is atoi do it alone ?
May 9, 2012 at 3:06pm UTC
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...
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.
May 9, 2012 at 3:52pm UTC
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
May 9, 2012 at 4:00pm UTC
He answered you. That's a good answer, even.
May 14, 2012 at 7:24pm UTC
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.