What's wrong with this setting?
I created a program called test:
#include<stdlib.h>
#include<iostream>
int main()
{
std::cout<<system("..\\add\\debug\\add.exe 4 8");
while(true);
return 0;
}
add.exe consists of
#include<stdlib.h>
int main(int argc,char **argv[])
{
int n=((unsigned)argv[1]);
int m=((unsigned)argv[2]);
return(n+m);
}
so when i run the test i get
6841420
The attempt was to have a test run added with parameters 4 and 8, and to add, return the sum of those values (12), and then the test would show this on the screen. How did I get 6841420 and how can I fix it?
The problem is that you are converting the pointer value to an integer. The arguments will be passed to your program as C ( const char*
) style strings . You must first convert them to string using API like atoi.
#include<stdlib.h>
int main(int argc,char *argv[])
{
int n= atoi(argv[1]);
int m= atoi(argv[2]);
return(n+m);
}
EDIT
As others have pointed out, you should also do some error checking to make sure there are actually 2 parameters per program.
source to share
It might be like a toy, but as FYI, you can't count on being able to return the entire range of integers from main (). First, system () uses different values as hourly values (like -1 and 127), so you won't be able to tell the difference between a failure and a legitimate result for one of these values. Second, shells can limit the range of the return value to only 8 bits (using the remaining bits for additional status information).
source to share
The answers about using atoi () or sscanf () to convert argv [] elements from strings to real integers are right at the point.
However, there is another problem with your test case. The return value system()
is the exit status for the running process, which is more than platform dependent. However, on most platforms, things are arranged so that the value 0
means the command is working fine and is ultimately called exit(0)
. Windows matches this.
The line cout<<system(...)
prints this status value. On many platforms (especially POSIX-compliant ones), if the process ran without abnormal termination, the low byte of the status code would be zero, and the high byte would be the value passed to exit()
, assuming the value is 255 or less.
In fact, using exit status to convey much more information than just the success / failure of the parent process is platform dependent, and there are much better ways to do it.
source to share