We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

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

cooling9999
cooling9999 asked
on
Medium Priority
239 Views
Last Modified: 2010-04-15
not sure how to scan a file's contents (numbers) into a matrix then print
after reading in file.

//scanning in #s//
for(i=0;i<SIZE;i++){
 for(j=0;j<SIZE;j++){
   fscanf(filename, "%f", a[i][j]);
  }
 }

//how do i bring the file into the program? do i need a pointer?//
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2006
Commented:
>//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
else
     //read from file here

Cheers!
sunnycoder

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2006

Commented:
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.

Cheers!
sunnycoder
sunnycoder's answer is currect,
you have to rewrite the fscanf like this,

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


Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.