Extracting from a file

A

andy.lee23

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.
 
D

David Resnick

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,829
Latest member
PIXThurman

Latest Threads

Top