Thread: scanf problem

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    305

    Angry scanf problem

    I'm trying to ask the user for a command and argument like:
    open blah
    would "open" blah. Well. If the user doesn't type an argument, it goes to the next line asking for an argument. Well, this isn't good. Here is the code:
    Code:
    scanf("%19s 29[^\n]", cmd, arg);
    which didn't work. Here's the other code that I tried:
    Code:
       for ( j = 0; c = getchar(); j++ ) {
    	if ( c == ' ' ){ i++; j = 0; continue; }
    	if ( c == '\n' ) break;
    	arg[i][j] = c;
        }
    which didn't work. If anyone knows how to do this, please tell me.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    36
    #include<stdio.h>

    int main(void)
    {
    char Cmd[20],Param[30],Temp[10];

    bzero(Cmd,sizeof(Cmd));
    bzero(Param,sizeof(Param));
    printf("Input command and parameter: ");
    scanf("%19[^ ^\n]%[ \t]%29[^\n]",Cmd,Temp,Param);
    printf("cmd: %s,param: %s\n",Cmd,Param);

    return(0);
    }

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Don't use scanf - its tricky to stop it reading past a newline

    Code:
    #include <stdio.h>
    
    int main ( ) {
        char buff[BUFSIZ];
        while ( fgets(buff,BUFSIZ,stdin) != NULL ) {
            char cmd[100], param[100];
            int res = sscanf( buff, "%s %[^\n]", cmd, param );
            if ( res == 1 ) {
                printf( "command '%s' with no arg\n", cmd );
            } else
            if ( res == 2 ) {
                printf( "command '%s' with arg '%s'\n", cmd, param );
            }
        }
        return 0;
    }
    
    Gets you
    hello
    command 'hello' with no arg
    hello world how are you
    command 'hello' with arg 'world how are you'
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with RPC and scanf
    By Ricardo_R5 in forum C Programming
    Replies: 11
    Last Post: 01-08-2007, 06:15 PM
  2. Quick problem aboutf scanf
    By BuezaWebDev in forum C Programming
    Replies: 4
    Last Post: 03-28-2005, 06:01 PM
  3. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 01:35 PM
  4. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-05-2005, 12:42 AM
  5. problem with looping scanf
    By crag2804 in forum C Programming
    Replies: 6
    Last Post: 09-12-2002, 08:10 PM