Extracting from a file

Discussion in 'C Programming' started by andy.lee23@gmail.com, Feb 3, 2005.

  1. Guest

    Hi, I've been learning C for a couple of weeks and I need some help. I
    have a text file and I want to extract integers from it to perform
    calculations.

    The format of the file is as follows:

    3 2
    3 5
    5 7


    I have written code to extract each line and put it into a string, but
    I don't know how to convert a string to an integer.

    Any help would be appreciated

    Thanks in advance.
     
    , Feb 3, 2005
    #1
    1. Advertising

  2. wrote:
    > The format of the file is as follows:
    >
    > 3 2
    > 3 5
    > 5 7
    >
    >
    > I have written code to extract each line and put it into a string, but
    > I don't know how to convert a string to an integer.
    >


    Seems like there are two options. For converting a string to an integer
    look at strtol. Or you can use sscanf. Here is an example program that
    handles this both ways. You should add suitable error checking, this
    code is not protected against bad input (e.g. check return of sscanf).
    #include <stdio.h>
    #include <stdlib.h>

    int main(void)
    {
    const char *str = "3 2";
    char *endptr;
    int i, j, l, m;

    i = strtol(str, &endptr, 10);
    j = strtol(endptr, NULL, 10);

    sscanf(str, "%d %d",&l,&m);
    printf("%d %d %d %d\n", i, j, l, m);
    return 0;
    }

    -David
     
    David Resnick, Feb 3, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gnaneshwar Babu

    extracting event logs to a file

    Gnaneshwar Babu, Dec 31, 2003, in forum: Perl
    Replies:
    0
    Views:
    744
    Gnaneshwar Babu
    Dec 31, 2003
  2. Guest
    Replies:
    3
    Views:
    3,766
    =?Utf-8?B?TG9yaSBNY0RvbmFsZA==?=
    Feb 23, 2004
  3. Bubbles
    Replies:
    0
    Views:
    468
    Bubbles
    Mar 3, 2004
  4. Bomb Diggy
    Replies:
    17
    Views:
    1,239
    Roedy Green
    Aug 29, 2003
  5. Replies:
    3
    Views:
    318
    Ron Natalie
    Jun 15, 2007
Loading...

Share This Page