简体   繁体   中英

C++ reading numbers from a text file into an array

Hello i am student of the first year thats why i got problem with such easy task. I am working currently on matrix calculator but in the very begging i occured some problems with reading numbers from a text file and printing them on screen Here is my code:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
 int main()
{
    ifstream infile;
    infile.open("matrix.txt", ios::in);
    //check for an error
    if(infile.fail())
    {
        cerr<<"Error opening file";
        exit(0);
    }
    //char sign;
    int n = 0;
    double matrix[n];
    while(!infile.fail())
    {
        infile >> matrix[n];
        n++;
        //if(infile.eof()) {break;}
    }

infile.close();


    for(int i = 0;i<9;i++)
    {
        cout << matrix[i]<<endl;
    }
return 0;
}

In the shortcut about the whole program it is supposed to read from a text file and calculate a determinant of 2x2 matrix or 3x3 matrix. If you can give me any ideas which will be useful in the future for example how i can check if the line in text file ended i would be thankful. But mostly i want to know what i am doing wrong. Thank's from above.

Consider the following lines of your code.

int n = 0;
double matrix[n];
while(!infile.fail())
{
    infile >> matrix[n];
    n++;
    //if(infile.eof()) {break;}
}

You will need to read the documentation of your compiler to find whether it supports variable length arrays. They are not allowed in standard c++, so if you want your program to be portable, you will need to stop using them.

Secondly, you allocate an array of size 0, which is not allowed (again, your compiler might allow it as a non-standard feature).

Thirdly, if the size of matrix is n , then matrix[n] will overflow.

Fourthly, checking the fail bit before extracting the value with infile >> matrix[n] is a bad idea. At some point you'll want to actually figure out how many valid values you have read, you'll find that it's simpler to test whether the extraction succeeded, after the extraction.

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