Why can't I get string input? - c

I was trying to simulate stack concept, and this is my code, blasts errors everywhere, from
the very first scanf,
to everywhere referring char* variables,
and eventually the stack pointer (I named it towerIndicator) doesn't change at all.
And then every typed input is somehow screwed: if I type '+314' to add 314 to the stack, it eventually add 3144, if all the problem above were somehow prevented while compiling.
gcc doesn't inform me any usable error message so I don't get where to go at all. Desperately requiring help here.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const int towerHeight = 32;
int tower[towerHeight];
int towerIndicator = 0;
/*
printf("%i개의 정수를 담을 수 있는 스택을 만들었습니다.\n", towerHeight);
printf("- '+'를 붙여서 정수를 담습니다.\n");
printf("- '-'를 입력해 정수를 빼냅니다.\n");
printf("- '?'를 입력해 스택을 확인합니다.\n");
printf("- '0'를 입력해 작업을 종료합니다.\n");
printf("명령을 입력해주세요.\n================================\n");
*/
char* command;
char* kindOfCommand[1];
char* actualCommand;
while(1) {
printf("> ");
scanf("%s", command);
printf("%s", command);
strncpy(*kindOfCommand, command, 1); kindOfCommand[1] = '\0';puts("#");
strncpy(actualCommand, command+1, strlen(command)-1);puts("$");
switch(**kindOfCommand) {
int i;
case '+':
if(towerIndicator<towerHeight) {
tower[towerIndicator] = atoi(actualCommand);
towerIndicator++;
printf("현재 %i개의 값이 있습니다.\n", towerIndicator);
} else printf("더 이상 넣을 곳이 없습니다.\n");
break;
case '-':
if(towerIndicator>0) {
towerIndicator--;
printf("%i\n", tower[towerIndicator]);
printf("현재 %i개의 값이 있습니다.\n", towerIndicator);
} else printf("더 이상 빼낼 값이 없습니다.\n");
break;
case '?':
default:
printf("[");
for(i=0; i<towerIndicator; i++) {
if(i==towerIndicator) printf("[%i]", tower[i]);
else printf("%i", tower[i]);
if(i!=towerIndicator-1) printf(" ");
}
printf("]\n");
break;
}
if(**kindOfCommand=='0') break;
}
}

There are quite a few modifications required here
loosely fixed may be in for a lot more fixes
// char* command; // <-- initialize this, failure in scanf other wise
char command[120] ;
assuming you are looking for a single character, don't complicate code
// char* kindOfCommand[1]; pointer not required
char kindOfCommand;
since you are using strncpy down somewhere
// char* actualCommand; // <-- initialize this
char actualCommand[126];
and the kindOfCommand code change
// strncpy(kindOfCommand, command, 1);
kindOfCommand = *command;// since you are taking single character
puts("#");
some more at switch
switch( kindOfCommand ) {
and while breaking
if( kindOfCommand == '0' ) break;
Also return before end
return 0;

I applied changes from kkk's answer, and getting input now works well.
char command[11];
char kindOfCommand;
char actualCommand[10];
while(1) {
printf("> ");
scanf("%s", command);
kindOfCommand = *command;
memset(actualCommand,0,sizeof(actualCommand));
strncpy(actualCommand, command+1, strlen(command)-1);
switch(kindOfCommand) { ... }
...
if(kindOfCommand=='0') break;
}
return 0;
}
I needed to solve the input getting screwed. It was because when actualCommand receives a new string from command and it's shorter than previous received string, the last few characters of the string was still remaining in actualCommand. So I put a memset to reset the variable every time the while loop loops. It's not a pointer, so sizeof() could do the work. Otherwise I should've to use strlen() to tell memset the length.

Related

Malloc and Realloc doesn't work (C11 - CLion)

#include <stdio.h>
#include <stdlib.h>
typedef struct Ogrenciler {
int no;
char adi[50];
char soyadi[50];
double vize;
double final;
double notu;
} Ogr;
int ogrenciSayisi = 0;
void KayitEkle(Ogr *ogrenci) {
int simdikiOgr = ogrenciSayisi;
if (ogrenciSayisi == 0) {
ogrenciSayisi++;
ogrenci = (Ogr *) malloc(ogrenciSayisi*sizeof(Ogr));
} else {
ogrenciSayisi++;
ogrenci = (Ogr *) realloc(ogrenci, ogrenciSayisi * sizeof(Ogr));
}
printf("No:");
scanf("%d", &ogrenci[simdikiOgr].no);
printf("Adi:");
scanf("%s", ogrenci[simdikiOgr].adi);
printf("Soyadi:");
scanf("%s", ogrenci[simdikiOgr].soyadi);
printf("Vize:");
scanf("%lf", &ogrenci[simdikiOgr].vize);
printf("Final:");
scanf("%lf", &ogrenci[simdikiOgr].final);
ogrenci[simdikiOgr].notu = (ogrenci[simdikiOgr].vize * 0.4) + (ogrenci[simdikiOgr].final * 0.6);
printf("Notu: %lf", ogrenci[simdikiOgr].notu);
printf("\n\n");
printf("Adi: %s\nNo: %d\nVize: %lf\nFinal: %lfNotu: %lf\n",
ogrenci[simdikiOgr].adi, ogrenci[simdikiOgr].no, ogrenci[simdikiOgr].vize, ogrenci[simdikiOgr].final,
ogrenci[simdikiOgr].notu);
}
int main() {
int c;
while (c != 5) {
printf("\n1-\tYeni Kayit Ekle\n2-\tKayit Sil\n3-\tKayitlari Listele\n4-\tOrtalama Hesapla\n5-\tCikis\n");
scanf(" %d", &c);
Ogr *ogrenci;
switch (c) {
case 1:
KayitEkle(ogrenci);
break;
case 2:
KayitSil(ogrenci);
break;
case 3:
KayitListele(ogrenci);
break;
case 4:
OrtHesapla(ogrenci);
break;
case 5:
printf("Cikiliyor");
break;
default:
printf("Gecerli bir girdi yapiniz\n");
break;
}
}
return 0;
}
As u can see, I use malloc() and realloc() for my typedef struct and I'm able to enter only one entry. When I tried adding a new entry (switch case: 1) it doesn't work and crashes after this section:
printf("No:");
scanf("%d", &ogrenci[simdikiOgr].no);
At first, I tried I used calloc(ogrenciSayisi*10*sizeof(Ogr)) but it was created only one space. After that, in the debugger (CLion's) after realloc section, ogrenci pointer becomes a null pointer.
Edit:
I'm not trying to return a value. As I know (int a) equals (int a[ ]) so KayitEkle(ogrenci) and void KayitEkle (Ogr ogrenci) seems legit to me. And my ogrenci should be empty in the first place so (Ogr *ogrenci=NULL) is correct as you said right?
Edit2:
In malloc section 10 is a mistake. I fixed it. I was trying something and I forgot to delete it.
You pass ogrenci pointer by value to KayitEkle(), you modify it's value inside it, yet not return it's modified value to main(). You need to pass ogrenci value using a pointer (ie. KayitEkle(&ogrenci)) or return the new value to the called (ie. ogrenci = KayitEkle(ogrenci)). Example below is with the latter.
ogrenci pointer is inside the while loop, so it will be reinitialized every time the loop runs, probably you meant to put it outside of the loop so it's value is preserved.
Local variables have undefined (read: any) value without initialization, so you need to explicitly initialize ogrenci to NULL, if you need. See Initialization.
You don't need to check for ogrenciSayisi == 0 when ogrenci == NULL, because realloc(NULL, ...) is equal to malloc(...). See realloc.
#include <stdio.h>
#include <stdlib.h>
typedef struct Ogrenciler {
int no;
char adi[50];
char soyadi[50];
double vize;
double final;
double notu;
} Ogr;
int ogrenciSayisi = 0;
// or void KayitEkle(Ogr **ogrenci) and then use *ogrenci
Ogr *KayitEkle(Ogr *ogrenci) {
int simdikiOgr = ogrenciSayisi;
ogrenciSayisi++;
ogrenci = realloc(ogrenci, ogrenciSayisi*sizeof(Ogr));
printf("No:");
scanf("%d", &ogrenci[simdikiOgr].no);
printf("Adi:");
scanf("%s", ogrenci[simdikiOgr].adi);
printf("Soyadi:");
scanf("%s", ogrenci[simdikiOgr].soyadi);
printf("Vize:");
scanf("%lf", &ogrenci[simdikiOgr].vize);
printf("Final:");
scanf("%lf", &ogrenci[simdikiOgr].final);
ogrenci[simdikiOgr].notu = (ogrenci[simdikiOgr].vize * 0.4) + (ogrenci[simdikiOgr].final * 0.6);
printf("Notu: %lf", ogrenci[simdikiOgr].notu);
printf("\n\n");
printf("Adi: %s\nNo: %d\nVize: %lf\nFinal: %lfNotu: %lf\n",
ogrenci[simdikiOgr].adi, ogrenci[simdikiOgr].no, ogrenci[simdikiOgr].vize, ogrenci[simdikiOgr].final,
ogrenci[simdikiOgr].notu);
return ogrenci;
}
int main() {
int c = 0;
Ogr *ogrenci = NULL;
while (c != 5) {
printf("\n1-\tYeni Kayit Ekle\n2-\tKayit Sil\n3-\tKayitlari Listele\n4-\tOrtalama Hesapla\n5-\tCikis\n");
scanf(" %d", &c);
switch (c) {
case 1:
ogrenci = KayitEkle(ogrenci);
break;
case 2:
ogrenci = KayitSil(ogrenci);
break;
case 3:
ogrenci = KayitListele(ogrenci);
break;
case 4:
ogrenci = OrtHesapla(ogrenci);
break;
case 5:
printf("Cikiliyor");
break;
default:
printf("Gecerli bir girdi yapiniz\n");
break;
}
}
// it's nice to free things
free(ogrenci);
return 0;
}
There are many mistakes. If you want to dynamically allocate memory with your function. A pointer of pointer must be used e.g. The instructions on the realloc line are also not correct, because if your re-allocation fails, you overwrite the old memory address and the pointer takes the same value as NULL.
And without getting off topic. You should also take precautions with the scanf function if you enter anything other than what the format expects (e.g. characters instead of numbers or vice versa), it is sure that the program will behave indeterminately, so you should anticipate this scenario.

Unix - Writing a line from a file to a char* var, then saving it in integers

Question: I have a file, called ATM1, and it is filled with strings, for example(this is the format for everyline): O ilan 123 456 Which means - O stands for open account, ilan is username, 123 is password, and 456 is initial amount in my bank account.
After opening the file, iterating with a while loop while(((ret_in = read (in1, &buffer1, BUF_SIZE)) > 0)), I want to get the line's details and store them in the appropriate variables. for example the first char will be stored in a variable called letter or msg[0] whatever is more convenient for you, then there is a space and then username, then password, and optional stuff like balance, or maybe another account id (for transfer money purposes).
Every ATM machine should be a thread, it has its own file, for now it is just one file "ATM1" because I want it to work in the beginning for at least one file.
Current Problem:
Segmentation fault in the OpenFile function. I'm still not able to store the line's values in the appropriate variables and called the switch statement for opening account, etc.
Here is the current code:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#define BUF_SIZE 8192
sem_t log;
void OpenNewAccount(int acc,int pw,int amount){
}
struct Account{
int number;
int password;
int balance;
};
//*Opens file for every ATM
void* openFile(void* args){
//To add later: while(true) { sleep(100); do next file's line }
//Open file
int* aargs = args;
int acc;
int pw;
int amount;
int target_acc;
int ret_in, in1,file;
char buffer1[BUF_SIZE];
int count = 0;
int i = 0;
char fn[5] = "ATM1";
char* msg;
file = open(fn,O_RDONLY|O_CREAT,0644);
while(((ret_in = read (file, &buffer1, BUF_SIZE)) > 0))
{
for(i; i<ret_in; i++)
{
if(buffer1[i]!='\n')
msg[i] = buffer1[i];
/* else{
if(count == 0){
count++;
break;
}
else
{
count = i + 1;
break;
}
}
*/
}
}
printf("%s", msg); //TEST: check msg
//Here we translate the message
/*
//Here we call the relevant function of the msg
switch (msg[count - 1]){
case 'O': OpenNewAccount(acc,pw,amount);
case 'D': Deposit(acc,pw,amount);
case 'W': Withdrawl(acc,pw,amount);
case 'B': Balance(acc,pw);
case 'Q': CloseAccount(acc,pw);
case 'T': Transfer(acc,pw,target_acc,amount);
}
*/
}
//*finish: Update log.txt and lock it
void WriteLog(char* msg){
int file;
char logName[8] = "log.txt";
sem_wait(&log);
file = open(logName,O_WRONLY|O_CREAT,0644);
strcat(msg,"\n");
write(file,&msg,strlen(msg));
close(file);
sem_post(&log);
}
int main(void)
{
int i,n,a;
sem_init(&log, 0, 1);
printf("Please enter the number of ATMs you want: \n");
scanf("%d", &n);
int bank; //bank with n ATMs
pthread_t thread[3];
printf("test\n"); //TEST: check msg
for(i = 0; i < 3; i++)
pthread_create ( &thread[i] , NULL , openFile , &i);
scanf("%d",&a);
}
Well, for one, you use i as an array index without ever initializing it. That could easily cause a SEGFAULT.
But honestly this whole thing is a mess. Your function names don't do what they say they do. You appear to be thrashing around almost randomly. I suggest you rethink your design from the beginning. Go through the "top down" design process you should have learned and figure out how to factor your code. Only then should you proceed.

Best choice for very simple lookup table

I am reading a file with commands that are [a-zA-Z][a-zA-Z0-9], i.e., two chars. There is a total of 43 different commands, and I would like to transform the two chars to a number (1..43).
How would you proceed? I was thinking on creating an array of 43 unsigned shorts (two bytes) each corresponding to the two chars of each command, and then doing something like:
//char1: first char of cmd, char2: second char of cmd, lut: array of 43 shorts.
unsigned short tag;
tag = (char1 << 8) | char2;
for(int i=1;i<=43;i++) {
if(tag==lut[i-1]) return i;
}
return 0;
The thing is I'm not sure if this is the best way for doing what I want. I guess that with just 43 elements it won't matter, but that list might increase in the future.
Here is a method I used on an old project. One big drawback to this method is the lookup table and enum are dependent on each other and need to be kept synchronized. I got this method from an online article quite a few years ago, but don't remember where. This is a complete example:
#include <stdio.h>
#include <string.h>
#define CMDSIZE 2
const char* cmd_table[] = { "qu",
"qr",
"fi",
"he"};
enum { CMD_QUIT,
CMD_QUIT_RESTART,
CMD_FILE,
CMD_HELP,
CMD_NONE };
int lookup(char command[])
{
int i = 0;
int cmdlength = strlen(command);
for (i = 0; i < cmdlength; i++)
{
command[i] = tolower(command[i]);
}
const int valid_cmd = sizeof cmd_table / sizeof *cmd_table;
for (i = 0; i < valid_cmd; i++)
{
if (strcmp(command, cmd_table[i]) == 0)
return i;
}
return CMD_NONE;
}
int main()
{
char key_in[BUFSIZ];
char command[CMDSIZE+1];
// Wait for command
do
{
printf("Enter command: ");
fgets(key_in, BUFSIZ, stdin);
key_in[strlen(key_in)-1] = '\0';
strncpy(command, key_in, CMDSIZE);
command[CMDSIZE] = '\0';
switch (lookup(command))
{
case CMD_QUIT:
printf ("quit\n");
break;
case CMD_QUIT_RESTART:
printf ("quit & restart\n");
break;
case CMD_FILE:
printf ("file\n");
break;
case CMD_HELP:
printf("help\n");
break;
case CMD_NONE:
if(strcmp(key_in, ""))
printf("\"%s\" is not a valid command\n", key_in);
break;
}
} while (strcmp(command, "qu"));
return 0;
}
EDIT:
I found the article I mentioned:
https://www.daniweb.com/software-development/cpp/threads/65343/lookup-tables-how-to-perform-a-switch-using-a-string

can anyone find why is ths program to solve postfix expression giving runtime error

I was trying to solve a postfix expression but i don't understand why is it giving runtime error.
code:
#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
struct stack
{
int top;
int n[100];
}s;
void push(int a)
{
s.n[s.top+1]=a;
s.top++;
}
void pop(char a)
{
int c,b;
b=s.n[s.top];
c=s.n[s.top-1];
s.top--;
switch(a)
{
case '+':
s.n[s.top]=b+c;
break;
case '-':
s.n[s.top]=b-c;
break;
case '*':
s.n[s.top]=b*c;
break;
case '/':
s.n[s.top]=b/c;
break;
}
}
int main()
{
s.top=-1;
int m,i,k;
char a[100],c[100];
scanf("%d",&m);
for(i=0;i<m;i++)
{
int j=0;
while(1)
{
scanf("%c",a[j]);
if(a[j]=='?')
break;
else if(a[j]==' ')
{
push(atoi(a));
}
else if(a[j]=='+'||'-'||'*'||'/')
{
pop(a[j]);
}
else
{
j++;
}
}
printf("%d",s.n[s.top]);
}
}
You code is hardly readble, still, I think, you need to change
scanf("%c",a[j]);
to
scanf(" %c",&a[j]); //note the space before %c, and scanf() expects pointer
for
& because as per the scanf() signature, it needs the address to store the scanned result.
leading space [] to stop scanning the previously pressed ENTER [\n] key.
Kindly Check the man page of scanf() for more details.
Also, as mentioned in Mr. #LPs 's answer, usage of push(atoi(a)); is very dangerous, in case a is not null-terminated.
Chnage scanf("%c",a[j]); to scanf("%c",&a[j]);. You need to pass the address to store the value of char. Also, you would further need to discard the extra character after each input from stdin.
I think that instruction push(atoi(a));is not safe, because of the array is not zero initialized, than atoi can fall into undefined behaviour.
Another thing is that with scanf with %c you can accept all chars (eg a, b,c) that make atoi fail.

Switch statement using string on an array

#include<stdio.h>
int main(){
char name[20];
printf("enter a name ");
scanf("%s",name);
switch(name[20]){
case "kevin" :
printf("hello");
break;
}
printf("%s",name);
getch();
}
It seems it will not work. Is this possible? I mean is there any way we can make a switch statement of a string. How to solve the problem, actually?
Switch statements in C aren't smart like one's found in other languages (such as Java 7 or Go) you cannot switch on a string (Nor can you compare strings with ==). Switch can only operate on integral types (int, char, etc).
In your code you call switch with: switch(name[20]). That means switch(*(name + 20)). In other words switch on the 21st char in name (because name[0] is the first). As name only has 20 chars you are accessing whatever memory is after name. (which could do unpredictable things)
Also the string "kevin" is compiled to a char[N] (where N is strlen("kevin") + 1) which contains the string. When you do case "kevin". It will only work if name is in the exact same piece of memory storing the string. So even if I copied kevin into name. It still would not match as it is stored in a different piece of memory.
To do what you seem to be trying you would do this:
#include <string.h>
...
if (strcmp(name, "kevin") == 0) {
...
}
String compare (strcmp) returns different values based on the difference in the strings. Eg:
int ord = strcmp(str1, str2);
if (ord < 0)
printf("str1 is before str2 alphabetically\n");
else if (ord == 0)
printf("str1 is the same as str2\n");
else if (ord > 0)
printf("str1 is after str2 alphabetically\n");
Side note: Dont use scanf("%s", name) in that form. It creates a common security problem use fgets like this: (there is a safe way to use scanf too)
#define MAX_LEN 20
int main() {
char name[MAX_LEN];
fgets(name, MAX_LEN, stdin);
...
Switch statements work on int values (or enum), but not on char arrays.
You could do
if (strcmp(name, "kevin")==0) {
printf("hello");
}
else if (strcmp(name, "Laura")==0) {
printf("Allo");
}
else if (strcmp(name, "Mike")==0) {
printf("Good day");
}
else {
printf("Help!");
}
There are plenty of ways to go about this! For example, use a...
3-letter hash
#include <stdio.h>
int main(){
char name[20];
printf("enter a name ");
scanf("%s",name);
switch((int)*name * (int)*(name+1) * (int)*(name+2)){
case (1275226) : // "kevin"
printf("hello %s.\n", name);
break;
case (1293980) : // "astro"
printf("welcome %s.\n", name);
break;
}
printf("%d",(int)*name * (int)*(name+1) * (int)*(name+2));
}
No, you cannot use the switch statement in C with the value of a string or character array. The closest alternative is to use some sort of data structure mapping strings to function pointers. The function pointer could be called after a string is used to look it up.
since the name is declared as a char type ,it would be better if you use "%c" instead of using "%s" inside the scanf() method.
You can use "hash-string.h" library that converts strings into hash code integer.
Create a header file and paste this code:
http://www.opensource.apple.com/source/gcc/gcc-5484/intl/hash-string.h
#include <stdio.h>
#include <stdlib.h>
#include "hash-string.h"
int main(){
char name[20];
printf("Enter a name: ");
scanf("%s",name);
unsigned long nameInt = hash_string(name);
switch(nameInt){
case 7458046 /* "kevin" */: { printf("Hello %s", name); break; }
default: { printf("You are not kevin"); }
}
printf("\n");
return 0;
}
Remember the rules while using switch statements.
Switch constraints
1. The controlling expression of a switch statement must have "integer type".
2. The expression of each case label shall be an integer constant expression and no two of
the case constant expressions in the same switch statement shall have the same value
after conversion. There may be at most one default label in a switch statement.
3. Any enclosed switch statement may have a default label or case constant expressions with values that duplicate case constant expressions in the enclosing switch statement.
If you are after performing specific actions for specific strings this implies you know the strings in advance. This in turn implies their number is limited, is countable, like for example a set of N commands:
const char * commands[] = {
"command-1",
"command-2",
...
"command-N"
}
To address those commands inside the array above from your code using a swtich you need to know their index, which is error prone. So number them, give them an ID:
enum Command_id {
NO_COMMAND,
COMMAND_1,
COMMAND_2,
//...
COMMAND_N,
};
Now put the two above together using a struct:
struct Command_info {
const char * command;
enum Command_id id;
} command_infos[] = {
{"", NO_COMMAND},
{"command-1", COMMAND_1},
{"command-2", COMMAND_2},
// ...
{"command-N", COMMAND_N},
};
Now you have nice mapping of strings and their related IDs. To be able to map from string to ID during runtime the mapping above needs to be searched. To do this in a efficient manner you want to us binary search. The C library proveids bsearch() for this. The only prerequsite is that the array to be searched need to sorted.
To sort use qsort() also proveid by the C library. For qsort() to work we you need a comparsion function:
int cmp_command_infos(const void * pvCI1, const void* pvCI2)
{
const struct Command_info * pCI1 = pvCI1;
const struct Command_info * pCI2 = pvCI2;
return strcmp(pCI1->command, pCI2->command);
}
Call qsort() like this
qsort(command_infos, sizeof command_infos / sizeof *command_infos, sizeof *command_infos, cmp_command_infos);
Now as the array is sorted one can look it up using bsearch(). For "COMMAND-2" this would look like this:
... = bsearch(&(struct Command_info){"COMMAND-2", NO_COMMAND}, command_infos, sizeof command_infos / sizeof *command_infos, sizeof *command_infos, cmp_command_infos);
Putting all this together could result in:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum Command_id {
NO_COMMAND,
COMMAND_1,
COMMAND_2,
//...
COMMAND_N,
};
struct Command_info {
const char * command;
enum Command_id id;
} command_infos[] = {
{"", NO_COMMAND},
{"command-1", COMMAND_1},
{"command-2", COMMAND_2},
// ...
{"command-N", COMMAND_N},
};
int cmp_command_infos(const void * pvCI1, const void* pvCI2)
{
const struct Command_info * pCI1 = pvCI1;
const struct Command_info * pCI2 = pvCI2;
return strcmp(pCI1->command, pCI2->command);
}
int main(int argc, char ** argv)
{
qsort(command_infos, sizeof command_infos / sizeof *command_infos, sizeof *command_infos, cmp_command_infos);
{
enum Command_id command_id = NO_COMMAND;
struct Command_info * pCI = bsearch(&(struct Command_info){argv[1], NO_COMMAND}, command_infos, sizeof command_infos / sizeof *command_infos, sizeof *command_infos, cmp_command_infos);
if (NULL == pCI)
{
printf("Command = '%s' is unknown\n", argv[1]);
}
else
{
printf("Command = '%s' --> ID = %d\n", pCI->command, pCI->id);
switch(command_id)
{
case COMMAND_1:
/* perform action on COMMAND 1 here */
break;
case COMMAND_2:
/* perform action on COMMAND 1 here */
break;
default:
/* unknow command, do nothing */
break;
}
}
}
}
Call it like:
./a.out command-1
giving:
Command = 'command-1' --> ID = 1
or:
./a.out command-bla
giving:
Command = 'command-bla' is unknown
or even
./a.out ""
giving:
Command = '' --> ID = 0

Resources