2
void readfromFile() {

    FILE *myFile;
    myFile = fopen("matrikel.txt", "r");

    //read file into array
    int numberArray[12];
    int i;

    if (myFile == NULL) {
        printf("Error Reading File\n");
        exit (0);
    }

    for (i = 0; i < 12; i++) {
        fscanf(myFile, "%d,", &numberArray[i] );
    }

    for (i = 0; i < 1; i++) {
        printf("Number is: %d\n\n", numberArray[i]);
    }

    fclose(myFile);
}

"matrikel.txt" contains

808098822790 

The number seems to be too long for the int numberArray[12], when running the code it prints a random number. When cutting some of the single integers from the end of the number it works, the maximum length seems to be 9.

I'm not quite sure but shouldn't the fscanf in the first for loop print one single digit number into each cell of numberArray[]?

5
  • 3
    You use the format "%d," for reading the numbers, that expects each number to have a comma after it. Perhaps you want to read each digit separately instead? Then I suggest you read each digit as a character instead, and then convert that character to its corresponding int value instead. Commented Jan 11, 2018 at 12:28
  • @Someprogrammerdude Okay, sounds like what I was wanting to do, but how can I? I was told to use an array, can I read each digit as a char into an array? Commented Jan 11, 2018 at 12:31
  • Why not read each digit, as a character, into a char variable? Then convert it (by doing e.g. char_variable - '0') and store that value in the int array you have? Commented Jan 11, 2018 at 12:33
  • I'm still not quite sure how to get it done, what I just tried didn't work. I will take a look at your idea when I have time, later today. Thanks for the idea :) Commented Jan 11, 2018 at 12:43
  • @user3121023 great, that just did it, thanks a bunch Commented Jan 11, 2018 at 12:45

1 Answer 1

5

A format specifier for scanf follows this prototype: %[*][width][length]specifier So, with %1d you will read a single number each time. But would be more simple to read each number as a char with fgetc(myFile);

 for (i = 0; i < 12; i++) {
     int c = fgetc(myFile);
     if(c == EOF)
        break;
     numberArray[i] = c - '0';
 }
Sign up to request clarification or add additional context in comments.

1 Comment

I will look into your post later, thanks for providing me with some answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.