fscanf into a 2d array in C












0














I want to scan elements from a txt into an array. The txt doesnt have how many rows or collumns i'm gonna have, it only contains a cordinate, and the elements of the array. It looks like this:



2,3
2,1
3,0
-


How can i put these numbers into an array so that array[0][0] will be 2 and array[1][0] will be 3 etc...



I want to make this work with other inputs as well.



My code so far :



The ?? is there because I have no idea how i should declare these if i dont even know how many rows or collumns every input txt will have.



#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE* in = fopen("in.txt", "r");

int x, y;

int array[??][??];

if (in == NULL) {
printf("Can't open in.txt");
fclose(in);
return 1;
}

if (fscanf(in, "%d,%dn", &x, &y) != 2) {
printf("Cant read file.");
return 2;
}

for (int i = 0; i < ??; i++) {
for (int j = 0; j < ??; j++)
fscanf(in, "%d", &array[i][j]);
}

return 0;


}










share|improve this question






















  • You say "it only contains a cordinate, and the elements" but I don't see the coordinate for array[0][0] in the example input.
    – Weather Vane
    Nov 22 at 19:02








  • 1




    Wouldn't it be array[0][1] that should be 3, and array[1][0] be the next 2? That would make more sense to me.
    – Some programmer dude
    Nov 22 at 19:06










  • The question is not clear to me; why do you read x and y? Are they actually the array bounds? But earlier you say you don't know the array bounds. It would improve the question to try and describe this better, as well as provide a realistic example of the file you are trying to read. For the file you provided you just need an array of fixed width 2 , since each row has 2 elements
    – M.M
    Nov 22 at 21:14


















0














I want to scan elements from a txt into an array. The txt doesnt have how many rows or collumns i'm gonna have, it only contains a cordinate, and the elements of the array. It looks like this:



2,3
2,1
3,0
-


How can i put these numbers into an array so that array[0][0] will be 2 and array[1][0] will be 3 etc...



I want to make this work with other inputs as well.



My code so far :



The ?? is there because I have no idea how i should declare these if i dont even know how many rows or collumns every input txt will have.



#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE* in = fopen("in.txt", "r");

int x, y;

int array[??][??];

if (in == NULL) {
printf("Can't open in.txt");
fclose(in);
return 1;
}

if (fscanf(in, "%d,%dn", &x, &y) != 2) {
printf("Cant read file.");
return 2;
}

for (int i = 0; i < ??; i++) {
for (int j = 0; j < ??; j++)
fscanf(in, "%d", &array[i][j]);
}

return 0;


}










share|improve this question






















  • You say "it only contains a cordinate, and the elements" but I don't see the coordinate for array[0][0] in the example input.
    – Weather Vane
    Nov 22 at 19:02








  • 1




    Wouldn't it be array[0][1] that should be 3, and array[1][0] be the next 2? That would make more sense to me.
    – Some programmer dude
    Nov 22 at 19:06










  • The question is not clear to me; why do you read x and y? Are they actually the array bounds? But earlier you say you don't know the array bounds. It would improve the question to try and describe this better, as well as provide a realistic example of the file you are trying to read. For the file you provided you just need an array of fixed width 2 , since each row has 2 elements
    – M.M
    Nov 22 at 21:14
















0












0








0







I want to scan elements from a txt into an array. The txt doesnt have how many rows or collumns i'm gonna have, it only contains a cordinate, and the elements of the array. It looks like this:



2,3
2,1
3,0
-


How can i put these numbers into an array so that array[0][0] will be 2 and array[1][0] will be 3 etc...



I want to make this work with other inputs as well.



My code so far :



The ?? is there because I have no idea how i should declare these if i dont even know how many rows or collumns every input txt will have.



#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE* in = fopen("in.txt", "r");

int x, y;

int array[??][??];

if (in == NULL) {
printf("Can't open in.txt");
fclose(in);
return 1;
}

if (fscanf(in, "%d,%dn", &x, &y) != 2) {
printf("Cant read file.");
return 2;
}

for (int i = 0; i < ??; i++) {
for (int j = 0; j < ??; j++)
fscanf(in, "%d", &array[i][j]);
}

return 0;


}










share|improve this question













I want to scan elements from a txt into an array. The txt doesnt have how many rows or collumns i'm gonna have, it only contains a cordinate, and the elements of the array. It looks like this:



2,3
2,1
3,0
-


How can i put these numbers into an array so that array[0][0] will be 2 and array[1][0] will be 3 etc...



I want to make this work with other inputs as well.



My code so far :



The ?? is there because I have no idea how i should declare these if i dont even know how many rows or collumns every input txt will have.



#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE* in = fopen("in.txt", "r");

int x, y;

int array[??][??];

if (in == NULL) {
printf("Can't open in.txt");
fclose(in);
return 1;
}

if (fscanf(in, "%d,%dn", &x, &y) != 2) {
printf("Cant read file.");
return 2;
}

for (int i = 0; i < ??; i++) {
for (int j = 0; j < ??; j++)
fscanf(in, "%d", &array[i][j]);
}

return 0;


}







c arrays scanf






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 18:59









Stan Marsh

216




216












  • You say "it only contains a cordinate, and the elements" but I don't see the coordinate for array[0][0] in the example input.
    – Weather Vane
    Nov 22 at 19:02








  • 1




    Wouldn't it be array[0][1] that should be 3, and array[1][0] be the next 2? That would make more sense to me.
    – Some programmer dude
    Nov 22 at 19:06










  • The question is not clear to me; why do you read x and y? Are they actually the array bounds? But earlier you say you don't know the array bounds. It would improve the question to try and describe this better, as well as provide a realistic example of the file you are trying to read. For the file you provided you just need an array of fixed width 2 , since each row has 2 elements
    – M.M
    Nov 22 at 21:14




















  • You say "it only contains a cordinate, and the elements" but I don't see the coordinate for array[0][0] in the example input.
    – Weather Vane
    Nov 22 at 19:02








  • 1




    Wouldn't it be array[0][1] that should be 3, and array[1][0] be the next 2? That would make more sense to me.
    – Some programmer dude
    Nov 22 at 19:06










  • The question is not clear to me; why do you read x and y? Are they actually the array bounds? But earlier you say you don't know the array bounds. It would improve the question to try and describe this better, as well as provide a realistic example of the file you are trying to read. For the file you provided you just need an array of fixed width 2 , since each row has 2 elements
    – M.M
    Nov 22 at 21:14


















You say "it only contains a cordinate, and the elements" but I don't see the coordinate for array[0][0] in the example input.
– Weather Vane
Nov 22 at 19:02






You say "it only contains a cordinate, and the elements" but I don't see the coordinate for array[0][0] in the example input.
– Weather Vane
Nov 22 at 19:02






1




1




Wouldn't it be array[0][1] that should be 3, and array[1][0] be the next 2? That would make more sense to me.
– Some programmer dude
Nov 22 at 19:06




Wouldn't it be array[0][1] that should be 3, and array[1][0] be the next 2? That would make more sense to me.
– Some programmer dude
Nov 22 at 19:06












The question is not clear to me; why do you read x and y? Are they actually the array bounds? But earlier you say you don't know the array bounds. It would improve the question to try and describe this better, as well as provide a realistic example of the file you are trying to read. For the file you provided you just need an array of fixed width 2 , since each row has 2 elements
– M.M
Nov 22 at 21:14






The question is not clear to me; why do you read x and y? Are they actually the array bounds? But earlier you say you don't know the array bounds. It would improve the question to try and describe this better, as well as provide a realistic example of the file you are trying to read. For the file you provided you just need an array of fixed width 2 , since each row has 2 elements
– M.M
Nov 22 at 21:14














2 Answers
2






active

oldest

votes


















0














You want to read in a list of value pairs? That sounds like you will need to have a (possibly long) array of sets of two numbers. Rather than remembering that X is the first and Y is the second, may I suggest setting up a structure to hold the values. Something like this should work:



int main()
{
FILE* in = fopen("lis.csv", "r");
int count=0;
int error=0;
int x, y;
typedef struct {
int x;
int y;
} COORD;
COORD array[999]={0};
if (in == NULL) {
printf("Can't open in.txt");
fclose(in);
return 1;
}
while(!feof(in))
{
if (fscanf(in, "%d,%dn", &x, &y) != 2) {
printf("Cant read file.");
error=1;
break;
}
array[count].x=x;
array[count].y=y;
count++;
}
return error;
}


I did not add anything bright for the error condition and it helps if you do something with the values after reading them in but you get the idea.






share|improve this answer

















  • 1




    Please see Why is while ( !feof (file) ) always wrong?
    – Weather Vane
    Nov 22 at 19:45










  • I was trying to give a hand with the fscanf and where to store the data. If it were me, I would have written it with while(fgets(linein,sizeof(linein), in)) It just happens that in this case, with GCC on Linux (and cygwin), the EOF test occurs after the last fscanf so this works fine. If the fscanf did not detect the EOF, the test of fscanf and break will avoid storing polluted data.
    – user1683793
    Nov 22 at 20:06



















0














You should use dynamic array allocation to scan elements from an unknown txt file into an array.
for C++ programmers the best solution is std::vector.
but C programmers should use alternative solutions.
please read this post: (std::vector alternative for C)






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436800%2ffscanf-into-a-2d-array-in-c%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You want to read in a list of value pairs? That sounds like you will need to have a (possibly long) array of sets of two numbers. Rather than remembering that X is the first and Y is the second, may I suggest setting up a structure to hold the values. Something like this should work:



    int main()
    {
    FILE* in = fopen("lis.csv", "r");
    int count=0;
    int error=0;
    int x, y;
    typedef struct {
    int x;
    int y;
    } COORD;
    COORD array[999]={0};
    if (in == NULL) {
    printf("Can't open in.txt");
    fclose(in);
    return 1;
    }
    while(!feof(in))
    {
    if (fscanf(in, "%d,%dn", &x, &y) != 2) {
    printf("Cant read file.");
    error=1;
    break;
    }
    array[count].x=x;
    array[count].y=y;
    count++;
    }
    return error;
    }


    I did not add anything bright for the error condition and it helps if you do something with the values after reading them in but you get the idea.






    share|improve this answer

















    • 1




      Please see Why is while ( !feof (file) ) always wrong?
      – Weather Vane
      Nov 22 at 19:45










    • I was trying to give a hand with the fscanf and where to store the data. If it were me, I would have written it with while(fgets(linein,sizeof(linein), in)) It just happens that in this case, with GCC on Linux (and cygwin), the EOF test occurs after the last fscanf so this works fine. If the fscanf did not detect the EOF, the test of fscanf and break will avoid storing polluted data.
      – user1683793
      Nov 22 at 20:06
















    0














    You want to read in a list of value pairs? That sounds like you will need to have a (possibly long) array of sets of two numbers. Rather than remembering that X is the first and Y is the second, may I suggest setting up a structure to hold the values. Something like this should work:



    int main()
    {
    FILE* in = fopen("lis.csv", "r");
    int count=0;
    int error=0;
    int x, y;
    typedef struct {
    int x;
    int y;
    } COORD;
    COORD array[999]={0};
    if (in == NULL) {
    printf("Can't open in.txt");
    fclose(in);
    return 1;
    }
    while(!feof(in))
    {
    if (fscanf(in, "%d,%dn", &x, &y) != 2) {
    printf("Cant read file.");
    error=1;
    break;
    }
    array[count].x=x;
    array[count].y=y;
    count++;
    }
    return error;
    }


    I did not add anything bright for the error condition and it helps if you do something with the values after reading them in but you get the idea.






    share|improve this answer

















    • 1




      Please see Why is while ( !feof (file) ) always wrong?
      – Weather Vane
      Nov 22 at 19:45










    • I was trying to give a hand with the fscanf and where to store the data. If it were me, I would have written it with while(fgets(linein,sizeof(linein), in)) It just happens that in this case, with GCC on Linux (and cygwin), the EOF test occurs after the last fscanf so this works fine. If the fscanf did not detect the EOF, the test of fscanf and break will avoid storing polluted data.
      – user1683793
      Nov 22 at 20:06














    0












    0








    0






    You want to read in a list of value pairs? That sounds like you will need to have a (possibly long) array of sets of two numbers. Rather than remembering that X is the first and Y is the second, may I suggest setting up a structure to hold the values. Something like this should work:



    int main()
    {
    FILE* in = fopen("lis.csv", "r");
    int count=0;
    int error=0;
    int x, y;
    typedef struct {
    int x;
    int y;
    } COORD;
    COORD array[999]={0};
    if (in == NULL) {
    printf("Can't open in.txt");
    fclose(in);
    return 1;
    }
    while(!feof(in))
    {
    if (fscanf(in, "%d,%dn", &x, &y) != 2) {
    printf("Cant read file.");
    error=1;
    break;
    }
    array[count].x=x;
    array[count].y=y;
    count++;
    }
    return error;
    }


    I did not add anything bright for the error condition and it helps if you do something with the values after reading them in but you get the idea.






    share|improve this answer












    You want to read in a list of value pairs? That sounds like you will need to have a (possibly long) array of sets of two numbers. Rather than remembering that X is the first and Y is the second, may I suggest setting up a structure to hold the values. Something like this should work:



    int main()
    {
    FILE* in = fopen("lis.csv", "r");
    int count=0;
    int error=0;
    int x, y;
    typedef struct {
    int x;
    int y;
    } COORD;
    COORD array[999]={0};
    if (in == NULL) {
    printf("Can't open in.txt");
    fclose(in);
    return 1;
    }
    while(!feof(in))
    {
    if (fscanf(in, "%d,%dn", &x, &y) != 2) {
    printf("Cant read file.");
    error=1;
    break;
    }
    array[count].x=x;
    array[count].y=y;
    count++;
    }
    return error;
    }


    I did not add anything bright for the error condition and it helps if you do something with the values after reading them in but you get the idea.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 22 at 19:13









    user1683793

    667613




    667613








    • 1




      Please see Why is while ( !feof (file) ) always wrong?
      – Weather Vane
      Nov 22 at 19:45










    • I was trying to give a hand with the fscanf and where to store the data. If it were me, I would have written it with while(fgets(linein,sizeof(linein), in)) It just happens that in this case, with GCC on Linux (and cygwin), the EOF test occurs after the last fscanf so this works fine. If the fscanf did not detect the EOF, the test of fscanf and break will avoid storing polluted data.
      – user1683793
      Nov 22 at 20:06














    • 1




      Please see Why is while ( !feof (file) ) always wrong?
      – Weather Vane
      Nov 22 at 19:45










    • I was trying to give a hand with the fscanf and where to store the data. If it were me, I would have written it with while(fgets(linein,sizeof(linein), in)) It just happens that in this case, with GCC on Linux (and cygwin), the EOF test occurs after the last fscanf so this works fine. If the fscanf did not detect the EOF, the test of fscanf and break will avoid storing polluted data.
      – user1683793
      Nov 22 at 20:06








    1




    1




    Please see Why is while ( !feof (file) ) always wrong?
    – Weather Vane
    Nov 22 at 19:45




    Please see Why is while ( !feof (file) ) always wrong?
    – Weather Vane
    Nov 22 at 19:45












    I was trying to give a hand with the fscanf and where to store the data. If it were me, I would have written it with while(fgets(linein,sizeof(linein), in)) It just happens that in this case, with GCC on Linux (and cygwin), the EOF test occurs after the last fscanf so this works fine. If the fscanf did not detect the EOF, the test of fscanf and break will avoid storing polluted data.
    – user1683793
    Nov 22 at 20:06




    I was trying to give a hand with the fscanf and where to store the data. If it were me, I would have written it with while(fgets(linein,sizeof(linein), in)) It just happens that in this case, with GCC on Linux (and cygwin), the EOF test occurs after the last fscanf so this works fine. If the fscanf did not detect the EOF, the test of fscanf and break will avoid storing polluted data.
    – user1683793
    Nov 22 at 20:06













    0














    You should use dynamic array allocation to scan elements from an unknown txt file into an array.
    for C++ programmers the best solution is std::vector.
    but C programmers should use alternative solutions.
    please read this post: (std::vector alternative for C)






    share|improve this answer


























      0














      You should use dynamic array allocation to scan elements from an unknown txt file into an array.
      for C++ programmers the best solution is std::vector.
      but C programmers should use alternative solutions.
      please read this post: (std::vector alternative for C)






      share|improve this answer
























        0












        0








        0






        You should use dynamic array allocation to scan elements from an unknown txt file into an array.
        for C++ programmers the best solution is std::vector.
        but C programmers should use alternative solutions.
        please read this post: (std::vector alternative for C)






        share|improve this answer












        You should use dynamic array allocation to scan elements from an unknown txt file into an array.
        for C++ programmers the best solution is std::vector.
        but C programmers should use alternative solutions.
        please read this post: (std::vector alternative for C)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 19:25









        Roohollah Yeylaghi Ashrafi

        1




        1






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436800%2ffscanf-into-a-2d-array-in-c%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Futebolista

            Lallio

            Jornalista