矢量下标超出范围,打印出矢量

时间:2014-07-18 08:41:29

标签: c++ vector

 #include <iostream>     
 #include <fstream>     
 #include <vector>
 #include <iterator>
 using namespace std;

 int main() {
     vector< vector<char> > MyVector;
     ifstream infile("text.txt", ifstream::binary);
     ofstream outfile("new.txt", ofstream::binary);

     if (infile) {
        // get length of file:
        infile.seekg(0, infile.end);
        int length = infile.tellg();
        infile.seekg(0, infile.beg);

        char * buffer = new char[length];
        cout << "Reading " << length << " characters... ";
        // read data as a block:
        infile.read(buffer, length);

        if (infile)
            cout << "all characters read successfully.";
        else
            cout << "error: only " << infile.gcount() << " could be read";

        MyVector.resize(1);
        for (int i = 0, j = 0; i < length; i++ ) {
            if (buffer[i] == ' ' && '\n') {
                j++;
                MyVector.resize(j + 1);
                MyVector[j].push_back(0x0D);
                MyVector[j].push_back(0x0A);            
            }
            else {
                MyVector[i].push_back(buffer[i]);
            }           
        }
        for (int i = 0; i < MyVector.size(); i++) { 
            outfile.write( &MyVector[i][], 1);
        }

        infile.close();
        outfile.close();
        // ...buffer contains the entire file...
        getchar();

        delete[] buffer;    
    }
    return 0;
}

我正在尝试将文本文件读入矢量,然后创建一个新文件,以便进行一些修改。

我真的不明白如何打印出来。

我猜这个循环有一些问题:

    for (int i = 0, j = 0; i < MyVector.size(); i++) {
        outfile.write(&MyVector[i][j], 1);
    }

其他地方也可能出现问题。

现在我得到:“矢量下标超出范围错误..”

1 个答案:

答案 0 :(得分:1)

有很多问题。以下是一些:

if (buffer[i] == ' ' && '\n')
你可能意味着:

if (buffer[i] == ' ' || buffer[i] == '\n')

下面:

MyVector[i].push_back(buffer[i]);
你可能意味着:

MyVector[j].push_back(buffer[i]);

下面:

outfile.write( &MyVector[i][], 1);
你可能意味着:

outfile.write(&MyVector[i][0], MyVector[i].size())
outfile.write("\n",1)

还要注意你正在重新发明轮子(这可能是一个很好的运动,如果它是一个练习)。实际上你应该使用std :: string和std :: getline逐行读取文本文件