调用返回数组的函数

时间:2015-03-30 11:29:04

标签: c++ visual-c++

我想调用一个返回数组的函数。它引发了一些异常 "访问违规写入位置0xABABABAB"

我试图将数组作为指针返回。如果我评论行

 convertor >> data[row][col];

有效。线路上似乎存在问题

convertor >> data[row][col];

任何帮助

#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>


using namespace std;


string * readcsvfile()
{
    string  * data = new string[];
    ifstream file("tradesheet5.csv");

    for (int row = 0; row < 4; ++row)
    {
        string line;
        stringstream newline;

        getline(file, line);

        if (!file.good())
            break;

        newline << line + ",\n";

        for (int col = 0; col < 11; ++col)
        {
            string val;
            getline(newline, val, ',');

            if (!newline.good())
                break;

            stringstream convertor(val);
            convertor >> data[row][col];
        }
    }
    return data;
}

void main()
{
   readcsvfile();
}

4 个答案:

答案 0 :(得分:0)

它看起来像你没有初始化字符串数组的任何大小,所以你正在访问未分配的内存。

答案 1 :(得分:0)

你可以替换

string  * data = new string[]; 

string data[4][11] = {};

如果您知道尺寸永远不会改变。 然后返回你说

return &data[0][0];

答案 2 :(得分:0)

如果你想拥有一个二维数组,我建议你不要使用string *或更糟糕的vector *

int main(void) //No void main... really, no
{
    std::vector<std::vector<std::string> > vCSVFile;
    readcsvfile(vCSVFile);
}

void readcsvfile(std::vector<std::vector<std::string> > &v)
{
    //[...]
}

甚至不考虑返回二维数组。它将被复制并且函数中的数组被破坏。使用大型CSV文件可能会浪费几分钟或更长时间。分配是一种方式,但这是一种不好的方式。

你的&#34; Parser&#34;不适用于常规CSV文件,请注意这些标记"可以包含逗号。你也需要处理它。

可能的CSV:

town, city, "wait, what", 1, 90

答案 3 :(得分:0)

vector <string> data;
vector <string> readcsvfile()
{
ifstream file("tradesheet5.csv");
for (int row = 0; row < 4; ++row)
{
    string line,val;
    vector <string> data;
    getline(file, line);

    if(!file.good())
        break;
    stringstream newline(line);
    newline << line + ",\n";

    if(!newline.good())
         break;

    while (getline(newline, val, ','))
         data.push_back(val);
}


return data;
}

int main()
{
readcsvfile();

cin.get();
 }
  1. 这里的问题是“数据”在for循环之外,它不包含任何信息。如何在循环外的“数据”中获取值,以便

    return data 
    
  2. 作品

    1. 如何将所有用逗号分隔的向量放入数组中?