ossobuko
ossobuko

Reputation: 871

How to read integers from a char string, when you dont know how many integers there is? (in C)

#include <stdio.h>
#include <string.h>

static const char nameOfFile[] = "blablabla.txt";
char lineG [128];

static char * readLine()
{
    static FILE *file;
    if(file == NULL)
        file = fopen ( nameOfFile, "r" ); //opens the file

    if ( file != NULL )
    {
        if( fgets ( lineG, sizeof (lineG), file ) != NULL ) //reads a line from file
            return lineG;
        else
            fclose ( file );
    }

    else perror ( nameOfFile ); 
    return NULL;
}

int main (void)
{
    char *line, a;
    line=readLine();
    char c;
    int a[30],b[30];

    sscanf(line,"%c %d%d%d%d",&c,a[0],b[0],a[1],b[1]);

    return 0;
}

As you see there i am trying to read int strings from a file. but i dont know how many int couples (like 12,23;) there will be. i am looking for a solution fits all.
txt file will be like this(two or more lines)

A 12,54;34,65;54,56;98,90   
B 23,87;56,98

Upvotes: 1

Views: 272

Answers (2)

hmjd
hmjd

Reputation: 121981

Use the %n format specifier and read one integer at a time. The associated argument for %n is populated with the index of the string where sscanf() read to. Description for format specifier n from the C99 standard:

No input is consumed. The corresponding argument shall be a pointer to signed integer into which is to be written the number of characters read from the input stream so far by this call to the fscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fscanf function. No argument is converted, but one is consumed. If the conversion specification includes an assignment suppressing character or a field width, the behavior is undefined.

A dynamically allocated array (using malloc()) would be required to store the ints and be extended (using realloc()) as required. Simple example for reading the ints (but not adding to an array):

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

int main()
{
    const char* in = "15 16 17 18";
    int i;
    int pos = 0;
    int total_pos = 0;

    while (1 == sscanf(in + total_pos, "%d%n", &i, &pos))
    {
        total_pos += pos;
        printf("i=%d\n", i);
    }

    return 0;
}

See online demo @ http://ideone.com/sWcgw0 .

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409216

To read X numbers, you simply read one at a time in a loop. The problem here though, is that the numbers are not separated by space but by commas and semicolons. This can not be easily be handled by a simple sscanf.

Instead I suggest you first extract the letter first in the line, and then use strtok to split the remaining on the semicolon, and then use strtok again to split on comma. Then you can use strtol to convert the numbers in the string into integer values.

Upvotes: 1

Related Questions