开发者

Read in exactly one or two strings

I have a program that accepts input from the command line. While all of the available commands are one string, several of the commands require a secondary string to further define the action.

e.g. "end" is one command, and "add foo" is a second.

My code handles the 2 string inputs fine, but when I try to access a single string command (such as "end") the program waits for more input instead of acting immediately.

Is there some way I can get the program to read in exactly one line (which may have up to two strings) rather than the way it is now?

Here's how it's currently implemented:

while(1)
    {
        scanf("%s%s", commandSt开发者_C百科ring,floorPath);

            if(!strcmp(commandString,"end") return;
            //I've got several of these as an "if / else", but there's no
            //need to reprint them here.

    }


Read the first string alone, and depending on the input decide if there is a need to read another string or not.

while(1)
{
    scanf("%s", commandString);
    if (requiresAnotherString(commandString))
    {
         scanf("%s", floorPath);
         // handle two string command
    }
    else
    {
         // handle one string command
    }
}


What MByD said, or alternatively, read a single line and then separately from the scanf() parse the line you read in and see if it is a one word command or a two word command and take the appropriate actions.


Here is an alternative:

int cmdFromStdin (char **cmd) {
    int count = 0, nBytes = 0;
    char *word, inline[BUFSIZ];

    if (nBytes = getline (inline, BUSIZ, STDIN)) < 0)
        return nBytes;
    for (word = strtok (inline, " ") ; word != NULL ; 
                    word = strtok (NULL, " "))
        cmd[count++] = word;
    return count;
}

It's been a while since I have coded in C, but I remember having problems with scanf (so I used to use getline()). The strtok function will parse out the string, on return you can check for success and work on the array cmd. I believe you have to include stdio.h, stdlib.h and string.h for this. My C is a bit rusty, so please excuse the syntax errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜