Reputation: 303
Working on a C knapsack program that will have a UI like interface, I have come to a point where I need for the user to be able to enter in characters for commands and while all of the ones which require only a simple one character input are quite simple I need to be able to allow the user to enter in a char
and an int
at the same time in the cases of adding or removing a number from the knapsack. While I know this can be done with two separate inputs from the user I'm wondering how can this be done in the same line without requiring the user to enter in two separate inputs. For example if the user types a 7
then it will add 7 to the knapsack.
CODE
#include <stdio.h>
#include "knapsack.c"
#include <stdlib.h>
#include <string.h>
int main()
{
listitemptr k2 = NULL;
char input[100];
int *returnval;
while(*input != 'q'){
printf("> ");
fgets(input, 100, stdin);
if(*input == 'p'){
KnapsackPrint(&k2);
}
else if(*input == 'a'){
printf("test\n");
sscanf(input, "%d", returnval);
printf("%d\n", *returnval);
}
else if(*input == 'r'){
}
else if(*input == 'l'){
}
else if(*input == 's'){
}
}
}
Upvotes: 1
Views: 1048
Reputation: 144780
There are many solutions for your user input proble. I would suggest you read one line at a time with fgets()
and parse it with sscanf()
:
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "knapsack.c"
int main() {
char input[100];
listitemptr k2 = NULL;
int i, returnval = 0;
char command;
for (;;) {
printf("> ");
if (!fgets(input, sizeof input, stdin))
break;
i = strspn(input, " \t\n"); /* skip blanks */
command = input[i++];
if (command == '#' || command == '\0') {
/* ignore comment lines and blank lines */
continue;
}
if (command == 'q' && input[i] == '\n')
break;
}
if (command == 'p') {
KnapsackPrint(&k2);
continue;
}
if (command == 'a') {
int item;
if (sscanf(input + i, "%i", &item) != 1) {
printf("invalid input\n");
continue;
}
KnapsackAdd(&k2, item);
continue;
}
// add more commands
printf("unknown command: %c\n", command);
}
return returnval;
}
Upvotes: 1