简体   繁体   English

从“ char *”到“ char”的无效转换

[英]invalid conversion from ‘char*’ to ‘char’

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 保罗

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 如果在命令行上传递“ 10”,则实际上是在传递字符数组

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

not the integer 10 . 不是整数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];

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. 问题是argv [2]是char *(C字符串)而不是char。

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. 请显示完整的错误消息和代码,但看来您需要将第二个参数作为char * argv []而不是char argv []来处理-即,作为字符数组列表,而不是单字符数组。

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”,并且在命令行中具有以下命令:

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'c',则需要执行以下操作:

char value = argv[3][0];

not

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

Even the value of "53" doesn't turn into an int. 即使“ 53”的值也不会转换为整数。 you can't do: 你不能做:

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

argv[2] is { '5', '2', '\\0' } . argv[2]{ '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). 编辑:顺便说一句,以上所有内容对于C都一样有效(因此,printf语句)。 It works EXACTLY the same in C++. 它在C ++中的工作原理完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM