pcomb
asked on
argv and static cast not ciompiling with Unix C++
int main(int argc, char argv[])
xx = static_cast<int>(argv[1]);
this compiles in visual studio but fails on argv error = "unix second argument of int main should be char *argv
"
If I change to *argv then stat_cast lines fails with
invalid static_cast from type char to type int
xx = static_cast<int>(argv[1]);
this compiles in visual studio but fails on argv error = "unix second argument of int main should be char *argv
"
If I change to *argv then stat_cast lines fails with
invalid static_cast from type char to type int
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You might need to include stdlib.h or cstdlib for atoi to work.
It would be interesting to know what it is you are trying to achieve here.
I am sure that there are neater ways to get where you are trying to go.
I am sure that there are neater ways to get where you are trying to go.
ASKER
am reading in a number of integer values and characters eg
./prog 1 2 3 4 +
if i use (int argc, char* argv[]) it does not cmpile in linux invalid static_cast from type char to type int as per my initial explanaton
thanks
./prog 1 2 3 4 +
if i use (int argc, char* argv[]) it does not cmpile in linux invalid static_cast from type char to type int as per my initial explanaton
thanks
"(int argc, char* argv[]) " is Perfectly correct.
However...
"xx = static_cast<int>(argv[1]); " is not, that is the error. As Tommy already said, you should use xx = atoi(argv[1]); for the first arg etc..
However...
"xx = static_cast<int>(argv[1]);
int main (int argc, char* argv[])
{
int xx;
if (argc > 1)
{
for (count = 1; count < argc; count++)
{
printf("argv[%d] = %s\n", count, argv[count]);
xx = atoi(argv[count]);
printf("argv[%d] = %d\n", count, xx);
}
}
}
{
int xx;
if (argc > 1)
{
for (count = 1; count < argc; count++)
{
printf("argv[%d] = %s\n", count, argv[count]);
xx = atoi(argv[count]);
printf("argv[%d] = %d\n", count, xx);
}
}
}
atoi will fail on characters. Are they always single characters like 1, 2, +, A, or can they be multiple, like 34, +:-, hi, ...?
If you are just hacking something simple together and want to only use single characters, then use static_cast<int>(argv[1][0 ]) to just pull the first character off of the argument.
If you want arbitrary length things, then why are you casting to int if it can be characters?
If you are just hacking something simple together and want to only use single characters, then use static_cast<int>(argv[1][0
If you want arbitrary length things, then why are you casting to int if it can be characters?