我正在编写简单的程序来解决填字游戏。我正在使用 getline 从输入中加载填字游戏,但我收到奇怪的“分段错误”消息,我真的不知道该怎么处理它。这是代码:
#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;
}
唯一重要的部分是 while 循环。当我输入此输入时:
Enter crossword:
+----+
| * |
| |
| * |
+----+
一切都很好,直到我进入脚本应该停止的第二个++----+,然后我得到分段错误。有人能帮助我吗?