为什么它跳过第一行

Why does it skip the first line?

本文关键字:一行 为什么      更新时间:2023-10-16

我遇到了这个问题,试图从输入文件中获取数据到我的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;
}

在您的while (getline(myfile1, line)) {循环之前,您有myfile1 >> line;,它将读取数据,当您第一次调用getline时立即丢弃。也许删除myfile1 >> line;行?