2016-10-14 88 views
-1

我遇到了這個問題,試圖將數據從輸入文件中輸入到我的vector<stack<string>>中。我不知道爲什麼,但看起來像我的代碼完全跳過輸入 這裏的第一行做的是輸入文件:它爲什麼跳過第一行?

1 D 
2 C A 
3 
4 B E 

這裏是我的代碼

ifstream myfile1; 
ifstream myfile2;           //take in the input file 

string line, filename, _block; 
vector<stack<string>> _stack; 
stack <string> _elements; 

cout << "Please enter name of beginning state" << endl; 
cin >> filename; 
// ------------------------------------------------------------------- 
//  OPEN FILE AND LOAD VERTICES AND EDGES IN APPROPRIATE VECTOR 
// ------------------------------------------------------------------- 
myfile1.open(filename.c_str()); 
if (myfile1.is_open()) 
{ 
    cout << "File found!" << endl; 
    myfile1 >> line;  
    while (getline(myfile1, line)) 
    { 
     int i; 
     string a; 
     stringstream ss (line); 
     ss >> i;     // "e" 
     cout<<"Test stupid: "<< i <<endl; 
     while(ss >> a) 
     { 
      _elements.push(a); 
      cout <<"Test dump: "<< a <<endl; 
     } 
     _stack.push_back(_elements); 
     //cout <<"Test: "<<_elements.top()<<endl; 
     num_of_stacks = _stack.size(); 
     num_of_elements = _elements.size(); 
    } 
    //cout <<"Test: "<<_elements.top()<<endl; 
    while(!_elements.empty()) 
    { 
     string w = _elements.top(); 
     cout <<"Test1: "<< w <<endl; 
     _elements.pop(); 
    } 
    cout <<"Test2: "<<num_of_stacks<<endl; 
    cout <<"Test3: "<<num_of_elements<<endl; 
} 
+0

而且當你用調試器瀏覽你的代碼時,你做了什麼觀察? –

+2

你認爲'myfile >>行'是什麼? – Barmar

+0

這並不是跳過第一行,因爲這只是跳過第一行的第一個數字。 – Barmar

回答

0

while (getline(myfile1, line)) {循環之前,你有myfile1 >> line;,它將讀取第一次撥打getline時立即丟棄的數據。也許刪除myfile1 >> line;一行?