Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Extracting from a file (http://www.velocityreviews.com/forums/t436766-extracting-from-a-file.html)

andy.lee23@gmail.com 02-03-2005 06:20 PM

Extracting from a file
 
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.


David Resnick 02-03-2005 06:33 PM

Re: Extracting from a file
 
andy.lee23@gmail.com 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


All times are GMT. The time now is 08:55 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.