Home > other >  sscanf not reading user input into struct member
sscanf not reading user input into struct member

Time:04-03

I'm attempting to read two pieces of data (an integer and a string) from user input, in one line, and store them into a struct.

code for struct:

// struct for message data
typedef struct message {
    int destPort;
    char messageData[100];
} message;

I've allocated memory for the struct like so:

message* newMsg = malloc(sizeof(message));

Obtaining user input:

fgets(userInput, 100, stdin);

I'm using sscanf like so:

if(sscanf(userInput, "%d[^ ] 0[^\n]", &newMsg->destPort, newMsg->messageData) != 2) {
                printf("Error: usage is <destination port #> <message>\n");
                exit(1);
            }

If user inputs "2002 hello", 2002 is read but hello isn't and therefore sscanf the if statement fails.

Any help would be greatly appreciated!

CodePudding user response:

Your scanf format specifier would match an input of "2002[^ ] hello".
The number matches the "%d" (or "%i"). The "[^ ]" would have to be literally there, because it is not one of the format specifers from those found in the documentation.
The sample input can be matched with "%d 0[^\n]", though that would require a char messageData[101];. Or match with "%d

  •  Tags:  
  • c
  • Related