【问题标题】:no conversion from 'const char *' to 'int'没有从 'const char *' 到 'int' 的转换
【发布时间】:2014-04-04 18:58:46
【问题描述】:

有人可以帮我解决我遇到的这个问题吗?在我的第一个“if”语句行中,我得到了“没有从 'const char *' 到 'int' 的转换。谁能告诉我我做错了什么?

char            Vtype,
            Vehicle;
int             HI,
            HO,
            MI,
            MO,
            Ctime,
            Catime,
            Btime,
            Basub,
            Ttime,
            Tasub;
double          Ctotal,
            Batot,
            Bbtot,
            Btotal,
            Tatot,
            Tbtot,
            Ttotal;
const double    C_Rate = 1.25,
            B1_Rate = 2.00,
            B2_Rate = 2.50,
            T1_Rate = 3.75,
            T2_Rate = 4.50;
cout << "TYPE OF VEHICLE: ";
cin >> Vtype;

    if (Vtype == "C" || Vtyp == "B" || Vtype == "T")
    {
        cout << "HOURS IN: ";
        cin >> HI;
        if (HI < 0 || HI > 23)
        {
            cout << "Hours cannot be less than 0 or greater than 23!\n";
            cout << "Please enter a valid hour.\n";
            cin >> HI;
        }

谢谢,

T

【问题讨论】:

  • 你能告诉我们Vtype的声明吗?听起来像是int,您将它与字符串进行比较。您是否尝试过将该声明更改为 std::string Vtype;
  • 嗨,Ed,这是我的声明。我把它留了一个字符,因为我只需要验证输入的字符。 char Vtype,车辆; int HI、HO、MI、MO、Ctime、Catime、Btime、Basub、Ttime、Tasub;双 Ctotal,Batot,Bbtot,Btotal,Tatot,Tbtot,Ttotal; const double C_Rate = 1.25, B1_Rate = 2.00, B2_Rate = 2.50, T1_Rate = 3.75, T2_Rate = 4.50;

标签: char int type-conversion


【解决方案1】:

如果 Vtype 是 char,将其与字符进行比较:

if (Vtype == 'C' || Vtype == 'B' || Vtype == 'T') {
}

编译器指责您将const char *int 进行比较,因为就C++ 而言,字符 一个整数。

或者,如果您需要将其与字符串进行比较,请将其声明为std::string

【讨论】:

  • 我认为这就是我正在做的事情。 'C' 是我试图比较 Vtype 的字符,如果 Vtype 被声明为 char,我不确定我做错了什么。
  • 在您的 OP 中,"C" 用双引号括起来。在 C++ 中,这是一个字符串文字。尝试单引号、撇号、刻度线:'C'。在这方面,我的示例与您的代码不同。这使它成为一个字符文字。有人可能会突然出现并在这里讨论语义,但实际上,"C" 将被视为指向字符数组的指针。如果您熟悉 Perl 或 JavaScript,您可能期望两个引号字符可以互换,或者几乎可以互换。在 C++ 中,它们不是。在 C++ 中,“C”是整数 67 的语义糖。
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
相关资源
最近更新 更多