C++ 从“int”到“const char*”的无效转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9702506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
invalid conversion from 'int' to 'const char*'
提问by GregT
I'm using gcc
on codeblocks and I'd like to write a function that uses an array of records.
我gcc
在代码块上使用,我想编写一个使用记录数组的函数。
However I keep getting the error:
但是我不断收到错误消息:
invalid conversion from 'int' to 'const char*'
The code:
编码:
#include <iostream>
#include <string>
using namespace std;
struct rendeles {
string nev;
int mennyiseg;
};
struct teaceg {
string nev;
int mennyiseg;
};
int szam;
struct rendeles rendelt [100];
struct teaceg cegek [100];
int h;
int hanyadikceg (string cegnev)
{
for (int i=0;i<szam;i++)
{
if (cegek[i].nev==cegnev)
{
return i;
}
}
return -1;
}
int main()
{
cout << "Hány db rendelés lesz ?sszesen?";
cin >> szam;
if (szam > 100)
{
cout << "Hiba: túl nagy a rendelések száma! (100 a maximum)";
return -1;
}
for (int i=0;i<szam;i++)
{
cout << "A(z) " << i+1 <<". cég neve:";
cin >> rendelt[i].nev;
cout << "A(z) " << i+1 <<". rendelés mennyisége:";
cin >> rendelt[i].mennyiseg;
}
cout << endl;
h = hanyadikceg('Lipton'); //the problem is in this line
cout << "Hanyadik cég a xyz:" << h;
for (int i=0;i<szam;i++)
{
cout << "A(z) " << i+1 << ". rendelés: " << rendelt[i].nev << " " << rendelt[i].mennyiseg << endl;
}
return 0;
}
What causes this error?
是什么导致了这个错误?
回答by Oliver Charlesworth
You need to use double-quotes ("
) for string literals, not single-quotes ('
).
您需要"
对字符串文字使用双引号 ( ),而不是单引号 ( '
)。
回答by Moo-Juice
You are using single quotes ('Lipton'
). Single quotes are for char
-literals.
您正在使用单引号 ( 'Lipton'
)。单引号用于char
-literals。
Use "Lipton"
, for a const char*
literal.
使用"Lipton"
, 作为const char*
文字。
回答by George Skoptsov
Change 'Lipton'
to "Lipton"
in the problem line and the compilation error will go away.
在问题行中更改'Lipton'
为"Lipton"
,编译错误将消失。
In C/C++, double-quoted expressions are strings (or, technically, string literals) and resolve to char *
or const char *
type, while single-quoted expressions are characters (or character literals) and resolve to char
type (which can be implicitly casted to int
). That explains your error: the compiler cannot convert the char
integer type to the const char *
that the function signature requires.
在 C/C++ 中,双引号表达式是字符串(或者,从技术上讲,字符串文字)并解析为char *
或const char *
类型,而单引号表达式是字符(或字符文字)并解析为char
类型(可以隐式转换为int
)。这解释了您的错误:编译器无法将char
整数类型转换const char *
为函数签名所需的类型。
回答by Lou
h = hanyadikceg('Lipton');
should be
应该
h = hanyadikceg("Lipton");