Home > Software design >  How to have multiple word input using sscanf?
How to have multiple word input using sscanf?

Time:11-18

Say I have:

char string[20][12];
string = "abcde bagfghabc cdfaga dnac eafagac cnaacaacaf"

I want to use sscanf so that the first, third and firth words are in one array and the others are in the other array. So every 2 words. (12 is the max word length) I tried doing

char odd[3][12];
char even[3][12];
int i = 0; 
while (i < 3) { 
   sscanf(string[i], odd[i], even[i]);
   i  ;
}

Thank you very much.

CodePudding user response:

You are attempting to solve the problem using sscanf. However, this function requires as a second parameter a format string, and you don't seem to be passing one.

Additionally, it does not make sense when calling sscanf in a loop, to start parsing at the start of the string in every loop iteration. Rather, you want to tell it to continue parsing at the end of the words that it has already parsed. Therefore, you must introduce an additional pointer variable which keeps track of how much of the string has already been parsed, and you must advance this pointer after every call to sscanf. For this, using the sscanf %n format specifier is useful.

Here is a solution as described above:

#include <stdio.h>

#define MAX_WORD_PAIRS 3
#define MAX_WORD_SIZE 12

int main( void )
{
    char  odd[MAX_WORD_PAIRS][MAX_WORD_SIZE];
    char even[MAX_WORD_PAIRS][MAX_WORD_SIZE];

    char string[] = "word1 word2 word3 word4 word5 word6";

    char *p = string;
    int num_pairs;
    int characters_read;

    //attempt to read one pair of words in every loop iteration
    for ( num_pairs = 0; num_pairs < MAX_WORD_PAIRS; num_pairs   )
    {
        //attempt to read a new pair of words
        if ( sscanf( p, "%s%s%n", odd[num_pairs], even[num_pairs], &characters_read ) != 2 )
            break;

        //advance pointer past the parsed area
        p  = characters_read;
    }

    //processing is complete, so we can now print the results

    //print odd words
    printf( "odd words:\n" );
    for ( int i = 0; i < num_pairs; i   )
    {
        printf( "%s\n", odd[i] );
    }

    printf( "\n" );

    //print even words
    printf( "even words:\n" );
    for ( int i = 0; i < num_pairs; i   )
    {
        printf( "%s\n", even[i] );
    }
}

This program has the following output:

odd words:
word1
word3
word5

even words:
word2
word4
word6
  • Related