-3

Hey guys im new here and im working on some code that is meant to read in 2 files. The file opens just fine, everything gets allocated ok later on down the line, however, when I read in individual lines from the file thats when I run into issues.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{   
char filename1[100];
    //Seting the file name for entery and seting the limit to 100
    //this one is for my matrix//
FILE* fp1;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename1);
    //scans in the name of the first file the file type needs to be 
included//  

fp1 = fopen(filename1, "r");
    //This will open the file as entered by the user//
if (fp1 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
int i;
int row1;
int col1;

fscanf(fp1, "%d,", &row1);
printf("%d \n ", row1);
fscanf(fp1, "%d,", &col1);  //WHY IS THIS SCANING WRONG!!!!//
printf("%d \n ", col1);
    //This will scan for the number of rows and columns in the matrix//
    //thats all for reading in the first file//

char filename2[100];
    //Seting the file name for entery and seting the limit to 100//
FILE* fp2;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename2);
    //Scans in the name of the first file//

fp2 = fopen(filename2, "r");
    //This will open the file as entered by the user//
if (fp2 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
return 0;
} 

This is what I get when i compile and run the full program. compiling

What should appear is a 5 and a 3 after loading in the data file.
the data is in the attached image but also here:

5
3
3.4,  6.5,  4.1
1.8,  3.3,  4.5
2.6,  7.4,  4.9
5.5,  6.1,  2.4
1.9,  2.7,  4.2

Everything else in my code works just fine with the exception of that.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Jay D
  • 1
  • 1
  • 1
    What is the exact expected input and output? to be clear what does you input file contains what is the final output of your program after execution – asio_guy Nov 14 '17 at 06:09
  • How does the file looks inside? – Elad Hazan Nov 14 '17 at 06:09
  • Sorry about that, its a CSV file where the first two values should be 5 and 3. As you can see 5 reads just fine but after that first line it wont read right. My guess is that its getting confused because of the comma but I dont know how to work around it if that is the case The entire file is a 5 X 3 matrix filled with some floating point values. – Jay D Nov 14 '17 at 06:12
  • I'm still unsure of your input and output still giving it a shot may be you need this fscanf(fp1, "%d,", &row1); <-- "%d," <-- comma after "%d" – asio_guy Nov 14 '17 at 06:28
  • I gave it a shot and It made no difference weather it was before the quote mark or not. As far as my input goes Ill upload a picture of it, there is no output for now at least. – Jay D Nov 14 '17 at 06:31
  • 1
    (1) Please specify more precisely what kind of “issues” you are encountering and what you expect the program to do. (2) Please post complete code that can be compiled and tested. (3) Please post sample data here as text, not elsewhere as an image. (4) Please review the help files so you will know these things without other users having to tell you. – Tom Zych Nov 14 '17 at 06:39
  • Sorry about that Ill edit it – Jay D Nov 14 '17 at 06:42
  • Your code works fine here. There might be an encoding problem with your data file. Open the data file with notepad, then do File-Save As, and under "Encoding" chose ANSI. BTW for testing purposes I'd hardcode the filenames so you don't have to type them in over and over again during your test process. – Jabberwocky Nov 14 '17 at 06:53
  • Michael Walz wow I cant believe it was that simple thank you so much. – Jay D Nov 14 '17 at 06:59

2 Answers2

1

Okay so based on your input this is is a minimal working code

    int i, j;
    int row1;
    int col1;
    float v;
    fscanf(fp1, "%d\n", &row1);
    fscanf(fp1, "%d\n", &col1);

    for ( i = 0 ; i < row1; i ++ )
    {
            for( j = 0 ; j < col1; j ++ )
            {
                    fscanf(fp1, "%f, ", &v);
            }
    }
asio_guy
  • 3,667
  • 2
  • 19
  • 35
  • 4
    Note that a trailing blank in a format string is lethal to interactive programs (see [Trailing blank in `scanf()` format string](https://stackoverflow.com/questions/19499060/) for information on why) and should generally be avoided. It's also unnecessary in that `%f`, like all the numeric conversion specifiers, skips leading white space anyway. – Jonathan Leffler Nov 14 '17 at 07:42
0

The primary responsibility you have when taking any user input is to validate the return from your input functions (whatever they may be) and if also required, validate the input falls within required range of values. But the minimum validation required is the return of the function you are using.

Also be aware that scanf (and family) can leave characters unread in the input buffer (e.g. stdin) that must be accounted for before the next call based on the format specifier being used. (e.g. numeric format specifiers (%d, %x, %o, etc.. will ignore leading whitespace for you, "%c" and "%s" do not remove leading whitespace (though it can be handled by explicitly including whitespace in your format string). this is also why fgets (or POSIX getline) are recommended for user input.

Putting the pieces together and using a VLA to hold the values, you can do something like the following. The program expects the filename as the 1st argument to the program, (it will read from stdin by default if no argument is given) It will then read the row and col values before reading row x col double values into a variable length array call arr. It closes the file and then outputs the values stored in the VLA in row x col form:

#include <stdio.h>

int main (int argc, char **argv) {

    int row = 0, col = 0;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* read and vailidate row & col */
    if (fscanf (fp, " %d %d", &row, &col) != 2) {
        fprintf (stderr, "error: failed to read row & col.\n");
        return 1;
    }
    double arr[row][col];                   /* VLA for arr */

    for (int i = 0; i < row; i++)           /* fill VLA */
        for (int j = 0; j < col; j++)
            if (fscanf (fp, " %lf%*c", &arr[i][j]) != 1) {
                fprintf (stderr, "error: line[%2d] read failure.\n", i);
                return 1;
            }

    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (int i = 0; i < row; i++) { /* output values stored in arr */
        for (int j = 0; j < col; j++)
            printf (" %5.2f", arr[i][j]);
        putchar ('\n');
    }
    return 0;
}

Example Use/Output

$ ./bin/arrrd <dat/arrrd.txt
 3.40   6.50   4.10
 1.80   3.30   4.50
 2.60   7.40   4.90
 5.50   6.10   2.40
 1.90   2.70   4.20

Look things over and let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85