I am writing simple program for solving crosswords. I am using getline to load crossword from input, but I am getting weird “Segmenation fault” messages and I really dont know what to do with it. Here is the code:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int** allocateCross(int rows, int columns)
{
int ** cross = new int*[rows];
for(int i=0;i<rows;i++)
{
cross[i] = new int[columns];
}
return cross;
}
void changeValue(int **cross, int rowPosition, int columnPosition, int value)
{
cross[rowPosition][columnPosition] = value;
}
void printCross(int ** cross, int rows, int columns)
{
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
cout << cross[i][j];
}
cout << endl;
}
}
void setCross(int ** cross, int rows,int columns, int spaces[], int numberOfSpaces)
{
for(int i=0;i<6;i++){
for(int j=0;j<6;j++){
changeValue(cross, i, j, 0);
}
for(int i=0;i<(numberOfSpaces*2);i=i+2)
{
changeValue(cross, spaces[i], spaces[i+1],1);
}
}
}
int testString(string stringToTest, const string allowedChars)
{
size_t found = stringToTest.find_first_not_of(allowedChars);
if(found != string::npos)
return false;
else
return true;
}
void wrongInput()
{
cout << "Wrong input." << endl;
exit(0);
}
int main()
{
string line;
string top;
string line_r;
bool stringTester;
int columns = 0;
int rows = 0;
getline(cin,line);
if(line!="Enter crossword:")
wrongInput();
getline(cin,line);
stringTester = testString(line,"+-");
if(stringTester != true)
wrongInput();
top = line;
top.erase(top.begin());
top.erase(top.begin()+(top.size()-1));
rows = top.size();
top = line;
getline(cin,line);
while(line != top)
{
columns++;
getline(cin,line);
}
int ** cross = allocateCross(rows,columns);
//int spaces[]={};
setCross(cross,rows,columns,spaces,0);
printCross(cross,rows,columns);
return 0;
}
The only important part is the while cycle. When i enter this input:
Enter crossword:
+----+
| * |
| |
| * |
+----+
Everything is fine until i enter the second +—-+ where the script shoud stop, then i get segmenation fault. Can someone help me please?
First of all, read the comments written.
The problem seems here:
Why this value (
6) is hardcoded? Why6and not42? You crossword in the example has three lines and four columns (3×4), but the cycle goes through 6×6 matrix.