【问题标题】:How to return a Multidimensional Array? Error C2440如何返回多维数组?错误 C2440
【发布时间】:2019-10-29 15:49:43
【问题描述】:

我打开了一个 .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++


【解决方案1】:

您应该使用 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;
}

【讨论】:

  • 请注意,auto 在 C++14 或更高版本之前不会这样工作。对于 C++11 及更早版本,您需要将返回类型实际声明为数组。
  • @Chipster 我们在 2019 年。如果有人使用 C++11 或更早版本而不是 C++14 或 C++17,他应该在问题中提及并相应地标记问题。跨度>
  • @ThomasSablik 嘿,谢谢,解决了。但现在我想做点别的。假设我希望 auto read_csv() 在其他文件中。如果我这样做,我会收到“找不到标识符”错误。我应该如何转发声明这个函数?转发声明为“auto read_csv();”给我错误:“'read_csv':在定义之前不能使用返回'auto'的函数”
  • @LuísF。如果要拆分声明和定义,则在这种情况下不能使用 auto 。我修正了我的答案
  • @ThomasSablik 谢谢。但是,我不得不改变:using CSV = std::array<:array>, 30>; to using CSV = std ::array<:array>, 600>;
猜你喜欢
  • 2014-07-02
  • 2016-04-17
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多