I am trying to input a 2d vector of string "t" times and make a grid of 2 * 2 size "t" times using C and the inputs can be integers 0 to 8 (inclusive) and ".", so i tried using a 2d vector of string but I am getting segmentation fault when accessing any element of a row > 0. I think it's because cin is buffered. Can anyone guide to how to debug this or use any other method.
here's the code inside main
int t;
cin>>t;
while(t--)
{
vector<vector<string> > grid(2);
vector<string> temp(2);
// vector<vector<char> > grid(2);
// vector<char> temp(2);
for(int i = 0; i < 2; i )
{
for(int j = 0; j < 2; j )
{
cout<<j<<" "; //loop is running when *enter* is pressed
cin>>temp[j];
// cin.get(temp[j]);
}
grid[i] = temp;
temp.clear();
}
cout<<"t-> "<<t<<" "<< grid[1][0]<<endl; //getting segmentation fault here
}
edit: if I put the vector<string> temp(2)
inside first loop then it's working but idk why coz i did use clear() so idk why is this the case.
CodePudding user response:
No, nothing to do with cin
being buffered.
The error is here
temp.clear();
That line changes the size of temp
to be zero, so on the next input cin >> temp[j];
you have a vector subscript error because temp
has zero size.
Just remove the line temp.clear();
and your code will work.