How to read Integer from a txt file

This is a discussion on How to read Integer from a txt file within the C Programming forums, part of the General Programming Boards category; The content of txt file is: item,coke,juice,beer 1, 12, 26, 17 2, 8, 18, 15 3, 25, 35, 20 i ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Location
    Hong Kong
    Posts
    13

    Post How to read Integer from a txt file

    The content of txt file is:

    item,coke,juice,beer
    1, 12, 26, 17
    2, 8, 18, 15
    3, 25, 35, 20

    i just need to read the integers, how can i ignore all the char?


    Code:
    int item,coke,juice,beer;
    infile = fopen("itemlist.txt", "r");
    if (infile == NULL) {
       printf("Fail to open itemlist.txt!\n");
       getchar();
       return -1;
    }
    fscanf(infile, "%d, %d, %d, %d", &item,&coke,&juice,&beer);
    fflush(stdin);
    fclose(infile);

  2. #2
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    How about just finding a function that reads in the entire first line and then DO NOTHING with the result of that at all?

    Then all subsequent operations will carry on from the second line as you want.

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Read one line at a time (fgets) and check it for numbers (sscanf).


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    DRK
    DRK is offline
    Registered User
    Join Date
    Jun 2009
    Posts
    109
    Don't do this
    Code:
    fflush(stdin);
    FAQ > Why fflush(stdin) is wrong

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. New program to read three numbered integer using getchar
    By Interista in forum C Programming
    Replies: 3
    Last Post: 11-03-2011, 01:45 PM
  2. how to read 4 consecutive bytes as an integer
    By *DEAD* in forum C Programming
    Replies: 8
    Last Post: 01-15-2007, 03:03 PM
  3. Read/Write long integer to file!
    By hyaku_ in forum C Programming
    Replies: 17
    Last Post: 11-02-2005, 02:06 PM
  4. How to read in an integer and display it again
    By axr0284 in forum C++ Programming
    Replies: 7
    Last Post: 12-07-2004, 12:37 PM
  5. Read Bytes From File Into Integer
    By ChadJohnson in forum C Programming
    Replies: 28
    Last Post: 08-16-2004, 11:57 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21