【问题标题】:The number of lines is always 0行数始终为 0
【发布时间】:2014-10-12 14:23:24
【问题描述】:

为什么行数总是0?应该是10,但是输出总是0。是不是方法有问题?

int main() {
    vector<double> doubleCoefficient; // vector to store unknown number of equations (double)

    /* Read from file and assign values to vector */

    //File stream object
    ifstream inputFile;
    //Open the txt file
    inputFile.open("test.txt");

    //search for the text file
    if(!inputFile.is_open())
    {
        cerr << "Error opening file \n";
        exit(EXIT_FAILURE);
    }
    else
    {
        cout << "File found and successfully opened. \n";
    }
    double x;

    while(!inputFile.eof()){

        inputFile >> x;
        doubleCoefficient.push_back(x);
    }

    int count =0;
    string line;
    while (getline(inputFile, line)){
        count++;
    }
    cout << "Number of lines in text file:" << count << endl;

    inputFile.close();
}

【问题讨论】:

    标签: c++ getline


    【解决方案1】:

    使用while(!inputFile.eof()) 你会转到文件的末尾,所以在那之后,你就不能读取行了。 您需要使用fseek()回到起点

    试试

    fseek ( inputFile , 0 , SEEK_SET );
    

    在计算行数之前。

    【讨论】:

    • 因为你从文件末尾开始计数,所以你什么都不会计数。
    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 2023-03-10
    • 2014-01-09
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多