Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c++ - Two-dimensional vector printing

I've got a two-dimension string vector that I need to print out. The whole program should read a line from a txt file, store each word from it as a different element and then push the "word vector" into a vector that contains for example 100 lines. I've got everything going, but the problem comes out when I have to print the vector. Every line can have a different number of words, ex:

I like cake

a lot.

So I can't use:

for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 3; j++)
    {
        cout << vec[i][j];
    }
}

because the second line doesn't contain 3 elements and the program closes.
Any idea how to do it? Note: my lecturer doesn't accept C++11, so a solution based on C++98 would be appreciated. This is my function:

void readline(vector<vector<string> >& lines, int size)
{
    vector<string> row;
    string line, word;
    fstream file;
    istringstream iss;
    int i;

    file.open("ticvol1.txt", ios::in);
    for (i = 0; i < size; i++)
    {
        getline(file, line);
        iss.str(line);
        while (iss >> word) row.push_back(word);
        lines.push_back(row);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can easily loop through the vector by its size, just use the size() member function:

for (int i = 0; i < vec.size(); i++)
{
    for (int j = 0; j < vec[i].size(); j++)
    {
        cout << vec[i][j];
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...