2014-10-05 39 views
1

我做的分配,以模擬確定性有限自動機,我已經從文本文件中該輸入:雷丁DFA從文件C++

4 
0 
0 0 2 a 1 b 3 
1 1 2 a 1 b 2 
2 1 2 a 1 b 3 
3 0 2 a 3 b 3 

其中第一行是狀態數,第二行是初始狀態,其他行依次爲:狀態編號,如果它是可接受的狀態,則爲1,否則爲0,轉換到另一狀態的次數,輸出字母以及從當前狀態進入該狀態的狀態。

該文件的DFA這是一個:

我,如果這個條件之一心不是真正找到文件中的一個錯誤:

  • 只有一個初始狀態

  • 每個狀態對於字母表中的每個字母都有一個且只有一個轉換

我使用ifstream的,但不知道如何按行讀入線和分離,以代幣(每個字符用空格分隔或輸入)這是我的代碼:

openingerror=1; 
ifstream file; 
file.open(filename); 
if(file.is_open()) { 

    openingerror=0; 

    NumberLetter dummy; 
    short int dCurrent,dIsfinal,dReach; 
    file >> total >> init; 
    dfa.resize(total); current.resize(total); 
    isFinal.resize(total); reach.resize(total); 
    deathState.resize(total); 

    for(short int i=0;i<total;i++){ 
     file >> dCurrent >> dIsfinal >> dReach; 
     current[i]=dCurrent; isFinal[i]=(bool)dIsfinal; reach[i]=dReach; 
     for (short int j=0;j<reach[i];j++){ 
      file >> dummy.l >> dummy.n; 
      dfa[current[i]].push_back(dummy); 
     }  
    } 

    cout << "File loaded" << endl; 
} 
else {  
    file.close(); 
    cerr << "Erro loading" << endl; 
} 
+1

http://stackoverflow.com/questions/6663131/reading-a-line-from-ifstream-into-a-string-variable – Ashalynd 2014-10-05 11:57:24

+0

可以讀取每個新行到一個字符串變量,然後使用這個變量作爲一個stringstream。 – Ashalynd 2014-10-05 11:58:01

+0

您可以將'freopen'和'scanf/cin'一起使用。 – saadtaame 2014-10-05 12:28:49

回答

0

我認爲你可以用「stringstream」解決這個問題。你可以閱讀每一行,你可以將每個值分配給適當的變量。此代碼將爲您的DFA提供矩陣實施,因此您可以使用此方法通過使用矩陣來解決問題。

char matrix[maxNumberofState][maxNumberofState];   
int tempInt; 
char tempChar; 

getline(file,line); 
stringstream valuesOfLine(line); 
valuesOfLine >> state>> acceptingBool >> tempInt >> tempchar; 

matrix[state][tempInt] = tempChar; 

valuesOfLine >> tempInt >> tempChar; 

while(!matrix[state][tempInt]){ 

matrix[state][tempInt] = tempChar; 
valuesOfLine >> tempInt >> tempChar; 

}