• C

prompt user for file, scan #s in file to matrix, print matrix

not sure how to scan a file's contents (numbers) into a matrix then print
after reading in file.

//scanning in #s//
   fscanf(filename, "%f", a[i][j]);

//how do i bring the file into the program? do i need a pointer?//
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

>//how do i bring the file into the program? do i need a pointer?//
Yes ... a FILE * ... use fopen to get a FILE *. fopen returns NULL if it could not open the file.

FILE * fptr =  fopen (filename,  "r");
if (!fptr)
      //error handling here
     //read from file here


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
About the reading code you have shown here

1. fscanf(filename, "%f", a[i][j]);
a[i][j] should be &a[i][j] ... you need to provide the address

2. make sure your data is floats and there are no field separators since your fscanf is reading only floats. If there are some other characters in the file, you need to handle them too!!
In my opinion it is much better to read in as string and then validate and convert it to desired format.

3. It would be a good idea to check for EOF in the inner loop. That way you would be able to gracefully handle incorrect input files which have lesser amount of data.

4. It is always safe to check return values of all system calls for error.

If you need any further clarifications, feel free to ask.

deepu chandranCommented:
sunnycoder's answer is currect,
you have to rewrite the fscanf like this,

FILE * fptr =  fopen (filename,  "r");
fscanf(fptr, "%f", a[i][j]);

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.