如何返回多维数组?错误C2440

How to return a Multidimensional Array? Error C2440

本文关键字:数组 错误 C2440 何返回 返回      更新时间:2023-10-16

我打开了一个.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::allocater>'">

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