【问题标题】:Turning a string into an int problems将字符串转换为 int 问题
【发布时间】:2019-04-26 14:26:12
【问题描述】:

所以我设法将字符串转换为 int。但是,在代码 #1 中,当我尝试将其分配给数组中的第一个插槽并打印出来时,它会打印“

atoi(menuAttributes[c].c_str()) = 20;
    quantity[d] = 3;
    string price[14];


    #1
    price[0] = atoi(menuAttributes[c].c_str()) * quantity[d];
    cout << price[0] << endl;


    #2
    cout << atoi(menuAttributes[c].c_str()) * quantity[d] << endl;

差不多,我希望 price[0] 等于 int 60,而不是 char '

编辑:已解决,感谢大家的帮助。菜鸟在这里,道歉!

【问题讨论】:

  • 语句后缺少半可乐 (;)?
  • 道歉我是新手,但是我知道,谢谢!但这不是导致问题的原因。有任何想法吗?谢谢
  • atoi(menuAttributes[c].c_str()) = 20;
  • price[0]std::stringatoi(menuAttributes[c].c_str()) * quantity[d] 不是 字符串。编译器不会抱怨那个赋值吗?
  • 您正在为不正确的字符串分配一个数字。价格数组必须是数值类型数组(int、float、...)才能具有值。

标签: c++ string int ascii


【解决方案1】:

这是因为你的price定义:

string price[14];

- 您已将其定义为一个由 14 个字符串组成的数组,并尝试为数组中的第一个字符串 (price[0]) 分配一个数值(从字符串的角度来看这是虚假的)。

一旦您将价格定义为int price[14],那么您将得到您所期望的

【讨论】:

  • 谢谢你,我很笨!
  • 一点也不,即使是专业人士也会犯这样的错误(唯一的区别是他们不会急于在 stackoverflow 上发布它))))
【解决方案2】:

price 需要定义为整数数组。当您尝试将整数值 60 存储在 price 中时,它会隐式转换为 (char)60,即 ASCII 表上的 &lt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2011-10-02
    • 2011-03-06
    • 1970-01-01
    相关资源
    最近更新 更多