简体   繁体   中英

Reading number of lines from file and using it in functions in c++

My problem may be trivial, but I don't know how to deal with it. I have a program that reads matrix from file and then collects it from file, displays it and performs a numeric method on it. When I insert number of unknowns(in this case it equals the number of lines in file) by cin I get everything right. But when I try to read number of lines from file and then read matrix, display it and perform method - although I get the number of lines correctly, the program reads matrix as if it consists of 0. Here is the code of counting lines:

int countLines(ifstream &file){
string line;
int l = 0;
do{
getline(file, line);
    l++;
}while(!file.eof());
return l;}

And here I try to use it:

string nameoffile = "";
 nameoffile = "Matrix1.txt";
  ifstream file;
    file.open(nameoffile.c_str());
    if (file.good()==true)
    {
        cout <<"The file is available<<endl;
        n = countLines(file);
        cout << n << endl;
        collectMatrix(file,n);
    }
    else
    {
        return 0;
    }
    displayMatrix(n);

For example, collectMatrix looks like that:

void collectMatrix(ifstream &file, int n){
for(int i = 0; i <n; i++)
{
    for(int j = 0; j <n; j++)
    {
        file>>A[i][j]; //matrix
    }
}      
for(int k=0; k<n; k++ )
{
    file>>b[k]; //vector of results
}            }

And all of it worked as long as I had cin>>n in the code instead of trying to read it from file. And to be honest, I have to read it from file but I'm not so good in programming, so I'd be thankful for any hints and help.

ifstream internally keeps track of how far into the file it has read. When your countLines method returns, the ifstream has read all the way to the end of the file, and it still holds the end of the file as its current position in the file when you pass it to collectMatrix. When you try to fill in the matrix, there is nothing left to read from the file, so the matrix values are not set.

You have a couple of options to fix this. The first is to calculate the size of the matrix as you are filling in the values. Your code seems to indicate that the matrix is square; if so, you can determine the size of the matrix simply by looking at the first line. The other, simpler, but much less efficient approach would be to just create a second ifstream with the same file and pass that to collectMatrix. This approach would be fairly slow, as you pass through the file twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM