【发布时间】:2020-03-19 09:37:30
【问题描述】:
我知道有可用的 FSA 实现,但我很想知道我在学习方面的错误在哪里。运行时错误通常发生在使用>> 从输入文件中读取时。
错误是“抛出异常:exercise.exe 已触发 断点”。
我问过我的同学,但他们也无法确定错误。
输入:
第一行:状态数
第二行:开始状态的#
第三行:接受状态数
接下来的几行:接受状态的#s
下一行:转换函数的数量
下几行:转换函数,形式为from to value,其中from和to是对应的状态, em>值是一个符号
下一行:我们需要检查是否接受的字符串数
接下来的几行:字符串本身
我的代码是:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
ifstream I("input.txt");
ofstream O("output.txt");
struct arrow {
int destination=-1;
char c='x';
arrow() {}
arrow(char val, int to) {
destination = to;
c = val;
}
};
struct node {
int name=-1;
bool accept=false;
int ars=0;
arrow* arrows=new arrow;
node() {}
node(bool isAccept, int whatName) {
accept = isAccept;
name = whatName;
}
};
class fsa {
int start;
node* states=new node;
public:
fsa(int n, int entrSt, int acceptSts) {
this->start=entrSt;
int* tempForAcceptStates = new int[acceptSts];
for (int i = 0; i < acceptSts; i++) I >> tempForAcceptStates[i];
for (int i = 0; i < n; i++) {
int wasNodeCreated = -1;
for (int j = 0; j < acceptSts; j++) {
if (tempForAcceptStates[j] == i) wasNodeCreated = i;
}
if (wasNodeCreated >= 0) states[i] = node(true, wasNodeCreated);
else { states[i] = node(false, i); }
}
int transitions;
I >> transitions;
for (int i = 0; i < transitions; i++) {
int from, to;
char val;
I >> from >> to >> val;
int temp = states[from].ars;
this->states[from].arrows[temp] = arrow(val, to);
states[from].ars++;
}
}
bool isRecognized() {
string str;
getline(I, str);
bool wasSymbolFound=false;
int currentNode = this->start;
for (int i = 0; i < str.length(); i++) {
int howManyArsCurrentNodeHas = states[currentNode].ars;
for (int j = 0; j < howManyArsCurrentNodeHas; j++) {
wasSymbolFound = false;
if (states[currentNode].arrows[j].c == str[i]) {
currentNode = states[currentNode].arrows[j].destination;
wasSymbolFound = true;
}
if (wasSymbolFound==true) break;
}
if (wasSymbolFound == false) return false;
}
if (states[currentNode].accept==true) return true; else return false;
}
};
void main() {
int n, entrSt, acceptSts;
I >> n >> entrSt >> acceptSts;
fsa A(n, entrSt, acceptSts);
int words;
I >> words;
for (int i = 0; i < words; i++) {
if (A.isRecognized()) O << "YES\n"; else O << "NO\n";
}
}
示例输入:
3
0
1
0
6
0 1 a
1 0 b
0 2 b
1 2 a
2 2 a
2 2 b
3
ab
aaa
abababab
对应的期望输出:
YES
NO
YES
【问题讨论】:
-
错误是什么?
-
@RomeoValentin 错误是“抛出异常:executive.exe 已触发断点”。
标签: c++ state-machine finite-automata