读取文件,尝试返回字符的二维数组

时间:2014-07-15 16:28:08

标签: c++ arrays c++11 character-arrays

嘿我试图接受函数参数中的文件并返回2D char数组,2D char指针或2D Vector ..不确定我应该使用哪个。我正在思考2D char数组以保持简单。基本上我不知道我要读入的文件中每行的长度,所以我不确定常规数组会有多长。我将一张普通纸可视化为一个非常大的二维阵列。这是我到目前为止所得到的,它仍然是虚空,因为我不知道该返回什么..

void ReadFile(std::string &file)
{

    //This is a file reader object. This time I am passing the name of the file as an argument into the constructor.

    std::ifstream TheReader(file);
    int lineLength = 0;
    int numLines = 0;

    char linebreak = 13;
    char singleCharacter;
    if (TheReader.is_open())
    {
        TheReader.get(singleCharacter);


        if (singleCharacter != linebreak)
        {
            lineLength++;
            TheReader.get(singleCharacter);
        }
        else if (singleCharacter == 13)
        {
            numLines++;
        }


        std::vector<std::vector<int>> myVector;
        lineLength = 0;
        numLines++;

        TheReader.close();

    }
    else
    {
        std::cout << "Error. Unable to open file" << std::endl;
    }

}

任何输入都是好输入! 干杯!

1 个答案:

答案 0 :(得分:1)

你可能想要返回一个std :: vector 像这样的东西

std::vector<std::string> ReadFile(const std::string &file)
{
    std::vector<std::string> output;
    std::ifstream TheReader(file.c_str());
    std::string line;
    while (std::getline(TheReader, line))
        output.push_back(line);
    return output;
}