christian
christian

Reputation: 105

Why is sscanf not reading anything

so i am trying to read strings using sscanf but it doesn't seem to read anything. I followed the tutrial and it looks very similar. I can't figuere out why it is not reading anything.

int main(){

    int status =0;
    int ret = 0;
    int arg;
    char *cmdLine = NULL;
    char *cmd=NULL;
    size_t n = 0;
    char *line = NULL;
    char *token =NULL;

    while (getline(&line, &n, stdin) > 0){
        //toekenize line
        token = strtok(line,";");

        //go thorugh and scan for cmds
        while(token !=NULL){
            // printf("token=%s\n", token);
            cmdLine = token;

            printf("%s\n", cmdLine);
            //read the commands
            ret=sscanf(cmdLine, "%31s %d", cmd, &arg);

            printf("%d\n", ret);

            token = strtok(NULL, ";");
        }//while loop 2
        //set line and n back to null and 0.
        line = NULL;
        n = 0;
    }//while loop 1

Upvotes: 0

Views: 359

Answers (1)

Kanji Viroja
Kanji Viroja

Reputation: 493

Try this:

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

int main(void)
{
    int status =0;
    int ret = 0;
    int arg;
    char *cmdLine = NULL;
    char cmd[100];
    size_t n = 0;
    char *line = NULL;
    char *token =NULL;

    if (getline(&line, &n, stdin) > 0)
    {
        //toekenize line
        token = strtok(line,";");

        //go thorugh and scan for cmds
        if(token != NULL)
        {
            // printf("token=%s\n", token);
            cmdLine = token;

            printf(">>>> %s \n", cmdLine);
            //read the commands
            ret = sscanf(cmdLine, "%s %d", cmd, &arg);
            printf(">>>> %d \n", ret);

            token = strtok(NULL, ";");

        }//while loop 2

        //set line and n back to null and 0.
        line = NULL;
        n = 0;
    }//while loop 1

    printf("Result string: %s and Arg: %d \n", cmd, arg);
}

Upvotes: 1

Related Questions