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