I'm working on a program that is supposed to take instruction from the user and do some stuff with it. It uses classes and objects to know what to do. However, some commands only require the user to input 2 things, and others 3, 4, etc. For example:
request> balance 2
This call is to retrieve the balance of customer 2. However this call:
request> deposit 2 30
This is supposed to deposit 30 dollars in to customer 2's acct.
How can I get the program to understand that the user can either be inputting 2 variables separated by a space, or more?
I have thought maybe taking the whole user input as a string and then parsing that may be easier...
char temp[257];
scanf("%s", temp);
However if you debug and output this so called string, it only outputs the last item the user entered.. so if a user entered
request> balance 3
It only grabs the 3 and stores it to temp...
I think you guys get the picture, I need to be able to feed the terminal multiple strings, ints, etc. and have it store each separate one into its own variable. Any help would be greatly appreciated!
Some dummy code for reference:
#include <iostream>
#include <stdio.h>
#include <cstdlib.h>
including namespace std;
int main()
{
char temp[257];
int x, y, z;
printf("request: ");
scanf("%s", temp); // I need this to be able to scan more than one
// thing, and know where to store them
scanf("%s %d %d", temp, x, y);
// because if I do this ^^, then it will just hang if I only need x and
// not y.
// Do some random stuff w/ variables now
return 0;
}
fgets(). You will read the entire line of text into a suitably-sizedchararray (checking for overflow, of course), and once the entire line of text is read, parse the read line for a valid command. Attempting to swallow input, one token at a time usingscanf(), is just a recipe for frustration. As you've already discovered. It can be made to work, but is surprisingly hard and full of minefields. Just usefgets.