-1

so I been trying to print 2D array using forloop

but if I print and see the result (each number is each line)

1
12
123
1234
12345
123456
1234567
12345678
123456789

its not printing line by line its printing first line and add extra line to it when it print.

I thought it was string stream problem so I tried

clear; empty; s.str(""); stringstream().swap(s);

but none of these worked.

    while(getline(file1,line1))
    {
        stringstream s(line1);
        while(getline(s,word,','))
        {
            student.push_back(word);

        }
            stack.push_back(student);
            s.str("");
    }
    file1.close();
for (int i = 0; i < stack.size(); i++)
{
    for (int j = 0; j < stack[i].size(); j++)
    {
        cout << stack[i][j];

    }
    cout << endl;
}

this is my coding to copy in informations from csv file.

I expect output to be

1
2
3
4
5
6
7
8
9

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Take a look at [here](https://stackoverflow.com/a/16447115/5517378) – NutCracker Oct 06 '19 at 07:17
  • 1
    Your question does not convey all relevant attributes of the problematic output. You will have to find a way to format it so that it becomes clearer. Consider changing your program to make much shorter output lines, that will help with making the cumulative aspect of the unwanted output clearer. Have a look here for formatting hints https://stackoverflow.com/editing-help What you need to achieve is a [mre]. I did something to improve the looks, but you need to work on the clarity. Consider describing the unwanted pattern in the output. – Yunnosch Oct 06 '19 at 07:24
  • And on making a MRE. – Yunnosch Oct 06 '19 at 07:32
  • @Yunnosch yes, but in step 1 `str.erase()` is called, which clears the string before reading. – Lukas-T Oct 06 '19 at 08:23

1 Answers1

0

Disclaimer: This answer is based on wild speculation, since you didn't provide much relevant information. I assume the following:

  1. student is a std::vector<string>
  2. stack is a std::vector<std::vector<string>>

Then your problem is, that you don't clear student. Just add a call to student.clear() before the inner loop and you should be fine.

More detailed explanation: In the inner loop you push a new string to student, then you push (thereby copying) student into stack. In the next iteration you push another value into student. It now contains two values and you push a vector with two values into stack. And so on and on.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30