tags:

views:

168

answers:

4

Hi Guys,

I have a,

int main (int argc, char *argv[])

and one of the arguements im passing in is a char. It gives the error message in the title when i go to compile

How would i go about fixing this?

Regards

Paul

A: 

You are probably not passing in what you think (though this should come from the command line). Please show the complete error message and code, but it looks like you need to deal with the second argument as char *argv[], instead of char argv[] -- that is, as a list of character arrays, as opposed to a single character array.

WhirlWind
char timer_unit; if (typeid(argv[2]) == typeid(timer_unit)) timer_unit = argv[2];
paultop6
Doesn't really help... what does typeid() do?
WhirlWind
@paultop6 -- please edit your question instead of putting details in the comments.
atzz
thanks for the tip atzz
paultop6
+2  A: 

If you only ever want the first character from the parameter the folowing will extract it from string:

char timer_unit = argv[2][0];

The issue is that argv[2] is a char* (C-string) not char.

Mark B
worked like a charm, thanks Mark B
paultop6
+3  A: 

When you pass command line parameters, they are all passed as strings, regardless of what types they may represent. If you pass "10" on the command line, you are actually passing the character array

{ '1', '0', '\0' }

not the integer 10.

If the parameter you want consists of a single character, you can always just take the first character:

char timer_unit = argv[2][0];
Nick Meyer
A: 

Everything stays strings when you pass them in to your program as arguments, even if they are single characters. For example, if your program was called "myprog" and you had this at the command line:

myprog arg1 53 c a "hey there!"

Then what you get in the program is the following:

printf("%d\n", argc);
for(int i = 0; i < argc; i++)
{
    printf("%s\n", argv[0]);
}

The output of that would be:

6
myprog
arg1
53
c
a
hey there!

The point being that everything on the command line turns into null-terminated strings, even single characters. If you wanted to get the char 'c' from the command line, you'd need to do this:

char value = argv[3][0];

not

char value = argv[3];  // Error!

Even the value of "53" doesn't turn into an int. you can't do:

int number = argv[2]; // Error!

argv[2] is { '5', '2', '\0' }. You have to do this:

int number = atoi(argv[2]);  // Converts from a string to an int

I hope this is clear.

Edit: btw, everything above is just as valid for C (hence the printf statements). It works EXACTLY the same in C++.

Kevin