2016-12-08 1 views
0

alors j'essaye de lire les chaînes en utilisant sscanf mais il ne semble pas lire quoi que ce soit. J'ai suivi le tutrial et ça a l'air très similaire. Je ne peux pas comprendre pourquoi il ne lit rien.Pourquoi sscanf ne lit rien

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 
+1

'ret = sscanf (cmdLine, "% 31s% d", cmd, &arg);': '' cmd' est null' 'char * cmd = NULL;. '->' char cmd [32]; ' – BLUEPIXY

+0

Vous n'avez alloué aucune mémoire pour' cmd' – Barmar

+1

Utilisez 'char cmd [32];' – Barmar

Répondre

0

Essayez ceci:

#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); 
}