You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++合并两个二维数组时第二个数组无法赋值到目标数组的问题

问题原因与解决方法

你的代码中,inventory2是int类型二维数组,而inventory3是string类型二维数组。直接将int值赋值给string变量时,无法完成正确的类型转换,这就是inventory3无法正确接收inventory2内容的核心原因。

修复后的代码

void sortInput(string inventory[10][3], int inventory2[10][2]) {
  string inventory3[10][5];
  for (int count = 0 ; count < 10 ; count++) {
    // 复制inventory的内容(string类型可直接赋值)
    for (int count2 = 0 ; count2 < 3 ; count2++) {
      inventory3[count][count2] = inventory[count][count2];
      cout << inventory3[count][count2] << "\t";
    }    
    // 复制inventory2的内容,需将int转换为string
    for (int count2 = 3, count3 = 0 ; count3 < 2 ; count2++, count3++) {
      // 使用to_string()完成整数转字符串
      inventory3[count][count2] = to_string(inventory2[count][count3]);
      cout << inventory3[count][count2] << "\t";
    }
    cout << endl;
  }
}

关键说明

  • 必须用to_string()函数把inventory2中的整数转换为字符串类型,才能正确赋值给inventory3的string元素。注意该函数要求编译环境支持C++11及以上标准。
  • 如果使用旧版C++标准,可通过stringstream实现类型转换,需先包含头文件<sstream>,循环内代码替换为:
stringstream ss;
ss << inventory2[count][count3];
inventory3[count][count2] = ss.str();

内容的提问来源于stack exchange,提问作者Dylan Raguseo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 09:15:38