Search code examples
cinputformatscanf

C language: How do I read an input like this "SomeWord(Int)", with no spaces, just a word and then a number inside round brackets


I need to take input from the user that is a single line and has 5 values which I extract from that input ('c' needs to be 5). The input is this format: "word(number) number word sentence". But the problem is with the "word(number)" input area. I cannot get it so that the values are read from that part of the input and stored in command, and num1. Below is the code I tried but it does not seem to be working.

c = sscanf (line, "%s(%d) %d %s %128[^\n]", command, num1, num2, message, message2);

When I make it so that the user enters "word (number) number word sentence" instead, with a space before the brackets, with also changing the code from %s(%d) to %s (%d), that seems to work. But I need it without any space between the values command and num1.


Solution

  • You will need to exclude the parenthesis from the first string. Assuming the "command" is strictly alphanumeric and underscore, you can do this:

    c = sscanf(line, "%[_a-zA-Z0-9](%d) %d %s %128[^\n]", command, &num1, &num2, message, message2);
    

    Also, you need ampersands on num1 and num2; perhaps those were typos?

    For safety, you should put length limits on command and message as you do for message2. Assuming 'char command[21], message[33];`, this would be:

    "%20[_a-zA-Z0-9](%d) %d %32s %128[^\n]"