首页 > 解决方案 > 如何返回多维数组?错误 C2440

问题描述

我打开了一个 .csv 文件并将其内容保存到一个二维数组中。当我尝试返回它的值时,我得到了提到的错误。

如果我不使用该函数或不返回数组,一切正常。做这个的最好方式是什么?

 string read_csv()
 {
     std::ifstream file_csv("C:\\DRT\\Lista de Materiais\\Lista.csv");
     string csv_temp[600][40]

     while (std::getline(file_csv, temp)) 
     {
         j = 1;
         while (temp != "")
         {
             pos = temp.find(",");
             csv_temp[i][j] = temp.substr(0, pos);
             temp = temp.substr(pos + 1, string::npos);
             j = j + 1;
        }
        i = i + 1;
    }
    return csv_lista;
}

int main()
{
    string csv[600][30];
    csv = read_csv();
}

C2440:'return':无法从 'std::string [300][30]' 转换为 'std::basic_string,std::allocator>'

标签: c++

解决方案


您应该使用 std::array 而不是 c 样式的数组来避免常见的初学者问题。您不能将 c 样式数组传递给函数或从函数返回 c 样式数组。数组衰减为一个指针,指针被传递。使用 std::array 解决了这个问题:

在 C++ 中,数组索引从 0 开始。

#include <array>
#include <fstream>
#include <string>
using std::string;

using CSV = std::array<std::array<string, 30>, 600>;

CSV read_csv();

int main() {
    auto csv = read_csv();
}

CSV read_csv() {
    std::ifstream file_csv("Lista.csv");
    CSV csv_temp;

    std::string temp;
    for (std::size_t i{0}; i < csv_temp.size() && std::getline(file_csv, temp); ++i) {
        for (std::size_t j {0}; j < csv_temp[i].size() && temp != ""; ++j) {
            auto pos = temp.find(",");
            csv_temp[i][j] = temp.substr(0, pos);
            temp = temp.substr(pos + 1, string::npos);
        }
    }
    return csv_temp;
}

推荐阅读