I've started studying C in the university. The professor gave us a task - to write a program that counts the number of comments in an another C program. We still haven't talked about operating with files. I found a similar solution - C Program to count comment lines (// and /* */) . Modified it a bit and it actually works but I can't understand the enum stuff. Tried to rewrite it without enumerations but with no success (cuz we have to explain how to program works). My question is - is there a way to solve it without enumerations?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fp;
int c, i=0;
char ch;
char path[150];
unsigned int chars = 0;
unsigned int multi = 0;
unsigned int single = 0;
enum states { TEXT,
SAW_SLASH,
SAW_STAR,
SINGLE_COMMENT,
MULTI_COMMENT } state = TEXT;
printf("Write file's path. Separate the folders with TWO back slashes (\\)\n");
scanf("%s", &path);
fp = fopen(path, "r");
if ( !fp )
{
fprintf(stderr, "Cannot open file %s\n", argv[1] );
}
else {
while((c=fgetc(fp)) != EOF){
switch( state ) {
case TEXT :
switch( c )
{
case '/' : state = SAW_SLASH; break;
default : break;
}
break;
case SAW_SLASH :
switch( c )
{
case '/' :
printf("case SLASH case / \n");
state = SINGLE_COMMENT;
break;
case '*' :
printf("case SLASH case * \n");
state = MULTI_COMMENT;
break;
default :
state = TEXT;
break;
}
break;
case SAW_STAR :
switch( c )
{
case '/' :
printf("case STAR case / \n");
state = TEXT;
multi++;
break;
case '*' :
break;
case '\n' :
printf("case SLASH case 'NEW LINE' \n");
multi++; // fall through
default :
state = MULTI_COMMENT;
break;
}
break;
case SINGLE_COMMENT :
switch( c )
{
case '\n' :
printf("case SINGLE case NEW LINE \n");
state = TEXT;
single++; // fall through
default :
break;
}
break;
case MULTI_COMMENT :
switch( c )
{
case '*' :
printf("case MULTI case * \n");
state = SAW_STAR;
break;
case '\n' :
break;
default :
break;
}
break;
default: // NOT REACHABLE
break;
}
}
fclose(fp);
printf( "File : %s\n", argv[1] );
printf( "Single-comment: %8u\n", single );
printf( "Multi-comment: %8u\n", multi );
}
return 0;
}
Since enum is equivalent to a bunch of #define 's, you can replace this part of the code:
enum states {
TEXT,
SAW_SLASH,
SAW_STAR,
SINGLE_COMMENT,
MULTI_COMMENT
} state = TEXT;
with:
#define TEXT 0
#define SAW_SLASH 1
#define SAW_STAR 2
#define SINGLE_COMMENT 3
#define MULTI_COMMENT 4
int state = TEXT;
Related
I'm writing a program to 'encrypt' an inputted string of text by using a switch statement to correlate the given character with a symbol, and output that symbol in the place of the character. I put it in a while loop, the idea being that it would loop the full switch function each time until the received character is EOF. On a guess, I believe it is looping through just the first character, because I don't advance the getchar() statement, but I'm not sure how to do that so any help would be greatly appreciated. I say this because if I use return instead of break, it closes the while loop and only takes that first letter, if I use a break then it spams the first 'encrypted' char.
#include <stdlib.h>
#include <stdio.h>
/* C program to encrypt a given text message, assuming all lowercase */
int main() {
int Input, Encrypted;
printf("Please type your message\n");
Input = getchar();
while (Input != EOF) {
switch (Input) {
case 'a':printf("!"); break;
case 'b':printf("#"); break;
case 'c':printf("#"); break;
case 'd':printf("$"); break;
case 'e':printf("%"); break;
case 'f':printf("^"); break;
case 'g':printf("&"); break;
case 'h':printf("*"); break;
case 'i':printf("`"); break;
case 'j':printf("~"); break;
case 'k':printf("-"); break;
case 'l':printf("_"); break;
case 'm':printf("="); break;
case 'n':printf("+"); break;
case 'o':printf("["); break;
case 'p':printf("{"); break;
case 'q':printf("]"); break;
case 'r':printf("}"); break;
case 's':printf(";"); break;
case 't':printf(":"); break;
case 'u':printf("|"); break;
case 'v':printf(","); break;
case 'w':printf("<"); break;
case 'x':printf("."); break;
case 'y':printf(">"); break;
case 'z':printf("'");break;
return 0;
}
}
return 0;
}
The simplest solution would be to remove the line
Input = getchar();
and to replace the line
while (Input != EOF) {
with:
while ( (Input=getchar()) != EOF && Input != '\n' ) {
Alternatively, if you find this while condition too confusing, you could also use an infinite loop, instead, like this:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
printf("Please type your message\n");
for (;;) //infinite loop, equivalent to while(true)
{
int c;
c = getchar();
if ( c == EOF || c == '\n' )
break;
switch ( c )
{
case 'a':printf("!"); break;
case 'b':printf("#"); break;
case 'c':printf("#"); break;
case 'd':printf("$"); break;
case 'e':printf("%%"); break;
case 'f':printf("^"); break;
case 'g':printf("&"); break;
case 'h':printf("*"); break;
case 'i':printf("`"); break;
case 'j':printf("~"); break;
case 'k':printf("-"); break;
case 'l':printf("_"); break;
case 'm':printf("="); break;
case 'n':printf("+"); break;
case 'o':printf("["); break;
case 'p':printf("{"); break;
case 'q':printf("]"); break;
case 'r':printf("}"); break;
case 's':printf(";"); break;
case 't':printf(":"); break;
case 'u':printf("|"); break;
case 'v':printf(","); break;
case 'w':printf("<"); break;
case 'x':printf("."); break;
case 'y':printf(">"); break;
case 'z':printf("'"); break;
}
}
return 0;
}
Note that most character sets (such as ASCII) store the characters a to z consecutively. With these character sets, you don't need the long switch statement. Instead, you can simplify it to the following:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
printf("Please type your message\n");
for (;;) //infinite loop, equivalent to while(true)
{
const char map[] = "!##$%^&*`~-_=+[{]};:|,<.>'";
int c;
c = getchar();
if ( c == EOF || c == '\n' )
break;
if ( 'a' <= c && c <= 'z' )
putchar( map[c-'a'] );
}
return 0;
}
SO i created a program that converts from infix to post fix and prefix which works just fine. The thing is that I am using C-LION which has its own debugger that allows me to go step by step and I do that the program works fine and outputs the expected results BUT then when I run it normally IT DOES NOT WORK AND GIVES ME A "main.c not working " ERROR.
This the main function that has the menu:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <tgmath.h>
char*infixToPostfix(char *infinx);
char* postixToinfix(char *infinx);
char* postixToprefix(char *infinx);
char* prefixToinfix(char *infinx);
char* prefixTopostfix(char *infinx);
char* infixToPrefix(char *infinx);
char*evaluate(char *infinx );
int exp_det(char*exp);
typedef struct node
{
char *op;
int p;
struct node *next; /* Pointer to the next node. Notice that the
existence of the structure tag enables us to declare its type. */
} node;
node *head=NULL; /* Global pointer that always points to the head of the
stack. */
int precedence(char symbol);
void add_stack(const node *p);
void pop(void);
int main(void)
{
char postfix[100];
int choice;
//converting from ininfinx to postfix
printf("\t\t***** Conversion Calculator 1.0 ******\t\t\n");
printf("\t\t1.Convert\n\t\t2.Evaluate\n\t\t3.Exit\nEnter Choice : ");
scanf("%d",&choice);
//switch (choice){
if (choice==1) {
printf("\n\t\t1.Input from File\n\t\t2.standered input\nEnter Choice :");
int ch2;
scanf("%d", &ch2);
switch (ch2) {
case 1:
printf("FILE MANGAMENT STILL NOT DONE !!!");
break;
case 2:
printf("Enter Expression : ");
char line[256];
scanf(" %[^\n]s", postfix);
char in2[100] = {'\0'};
char in3[100] = {'\0'};
char *conv;
char *conv2;
strcpy(in2, postfix);
strcpy(in3, postfix);
int exp = exp_det(in2);
if (exp == 1) {
printf("\nThis is a Prefix expression do you want to\n\t\t1.Infix\n\t\t2.Postfix\n\t\t3.Both\nEnter Choice :");
int ch3;
scanf("%d", &ch3);
switch (ch3) {
case 1:
conv = prefixToinfix(in3);
printf("Expression in Infix form: %s \n", in3);
break;
case 2:
conv = prefixTopostfix(in3);
printf("Expression in Postfix form: %s \n", in3);
break;
case 3:
conv = prefixToinfix(in3);
conv2 = prefixTopostfix(postfix);
printf("Expression in Infix form: %s \n", conv);
printf("Expression in Postfix form: %s \n", conv2);
break;
default:
printf("ERROROR WHEN EXPRESSION IN PREFIX ");
break;
}
} else if (exp == 2) {
printf("\nThis is a Infix expression do you want to\n\t\t1.Prefix\n\t\t2.Postfix\n\t\t3.Both\nEnter Choice :");
int ch3;
scanf("%d", &ch3);
switch (ch3) {
case 1:
printf("Expression in prefix form: %s \n", infixToPrefix(postfix));
break;
case 2:
printf("Expression in Postfix form: %s \n", infixToPostfix(postfix));
break;
case 3:
printf("Expression in prefix form: %s \n", infixToPrefix(postfix));
printf("Expression in Postfix form: %s \n", infixToPostfix(postfix));
break;
default:
printf("ERROROR R");
break;
}
} else if (exp == 3) {
printf("This is a Postfix expression do you want to\n\t\t1.Infix\n\t\t2.Prefix\n\t\t3.Both\nEnter Choice :");
int ch3;
scanf("%d", &ch3);
switch (ch3) {
case 1:
printf("Expression in Infix form: %s \n", postixToinfix(postfix));
break;
case 2:
printf("Expression in prefix form: %s \n", postixToprefix(postfix));
break;
case 3:
printf("Expression in Infix form: %s \n", postixToinfix(postfix));
printf("Expression in Prefix form: %s \n", postixToprefix(postfix));
break;
default:
printf("ERROR... 3:(\n");
break;
}
}
break;//for the switch with ch2 case 1
default:
printf("ERROR... 2:(\n");
break;
}
//break;
}if(choice==2) {
printf("Enter Expression : ");
scanf(" %[^\n]s", postfix);
char in2[100] = {'\0'};
char in3[100] = {'\0'};
char *conv;
char *conv2;
strcpy(in2, postfix);
conv = evaluate(in2);
printf("\nExpression evaluated = %s \n", conv);
//break;
}if(choice==3) {
printf("BYE...... :D\n");
}
system("PAUSE");
}
OK Now after much trials I am starting to think that the problem is in the conversion itself. This is one of the functions i am using for me it looks fine. If anyone has another opinion help is greatly appropriated.
char* infixToPostfix(char *infinx){
char* token;
char * infinx1=malloc(sizeof(infinx)+1);
infinx1=strcpy(infinx1,infinx);
token = strtok(infinx1," ");
char* res;
res=malloc(sizeof(infinx)+sizeof(head->op)*strlen(infinx));
strcpy(res," ");
if(*token=='\n' ){token=strtok(NULL," ");}
while( token != NULL ) {
node n;
n.op=token;
n.p=precedence(*token);
if(isalpha(*token) || isdigit(*token)){
// strcat(result,infinx[i]);
//printf("%c",infinx[i]);
res=strcat(res,token);
res=strcat(res," ");
}
//case when encounter a left paranthessisis
else if(*token=='(' || *token==')'){
if (*token=='('){
add_stack(&n);
}else if(*token==')') {
while (*head->op != '(') {
// strcat(result, n.op);
//printf("%c",(char)head->op);
res=strcat(res,head->op);
res=strcat(res," ");
pop();
}
pop();
}
}
//if head if null meaning the stack is empty or if the presendance of the head is less thatn or equal to new character
else if(head==NULL || head->p < n.p ){
if (head->p == n.p){}
add_stack(&n);
}
//in case the head has higher presendance he we pop and print untill we reach the same presedance
else {
while( head!=NULL && head->p >= n.p){
//strcat(result,n.op);
//printf("%c",(char)head->op);
res=strcat(res,head->op);
res=strcat(res," ");
pop();
}
add_stack(&n);
}
token=strtok(NULL," ");
}
while(head!=NULL){
//strcat(result,head->op);
//printf("%c",(char)head->op);
res=strcat(res,head->op);
res=strcat(res," ");
pop();
}
return res;
}
This is the answer to your question "So your saying I should define them outside the switch statement?" which reflects correctly one of the problems in your code.
Either: You can define them outside to solve the issue.
Or: You can introduce appropriate block scopes to solve the issue.
As the former is trivial, I will elaborate the latter:
1. Scope and Variables
The life-time of a local variable starts at its declaration and ends with surrounding block scope.
Example:
int main()
{
int a = 0; /* a starts to live. */
{ /* new scope */
int b = 1; /* b starts to live */
int a = 2; /* a new a starts to live. (The one of out scope is eclipsed.) */
} /* Life of b and the inner a ends. The eclipsed outer a becomes visible again. */
return 0;
}
2. switch and case
In opposition to other languages (like e.g. Pascal), the C switch statement is rather a "goto depending on expression" than a multiway branching with multiple alternatives. (This does not mean that switch cannot be used for the latter but it can be used different as well.) (Please, see Wikipedia: Control Flow: 5.2 Case and switch statements to understand what I mean.)
Imagine the following (wrong) code:
#include <stdio.h>
int main()
{
goto L1;
int i = 1;
L1:
printf("%d\n", i);
return 0;
}
The goto L1; skips the declaration of int i = 1; but after L1: it is used in printf() – ouch!
Out of curiosity, I tried it in ideone.com – it compiled and ran without complaints. Output was 0 although it could have been as well 1, 2, or any other number which can be stored as int.
This is the same in the following (wrong) sample:
#include <stdio.h>
int main()
{
int cond = 2;
switch (cond) {
case 1:
printf("case 1\n");
int i = 1;
case 2:
printf("case 2: %d\n", i);
} /* Here ends the life-time of i */
return 0;
}
Again, I compiled and tested in ideone.com.
Output was case 2: 0. Ouch again!
Solution
To mimic multi-branching correctly, the following things are necessary:
End each case with a break.
Start a scope after each colon of a case.
End this scope before the corresponding break.
Example again:
#include <stdio.h>
int main()
{
int cond = 2;
switch (cond) {
case 0: case 1: { /* <- start scope */
int i = 1;
printf("case 1: %d\n", i);
} break; /* <- end scope and jump to end of switch */
case 2:
printf("case 2: %d\n", i); /* i is recognized as unknown identifier */
}
return 0;
}
Compiled in ideone:
prog.c: In function ‘main’:
prog.c:12:34: error: ‘i’ undeclared (first use in this function)
printf("case 2: %d\n", i); /* i is recognized as unknown identifier */
^
As the scope of variable i is limited to the range from the possible entrance (case 0: case 1:) until the possible exit (break) – no other possible code path may access it.
I'm attempting to make use of a switch() statement by using keywords instead of an integer. I've written my problem into a more simple and direct example to better point out my goal here. My relevant code:
#include <stdio.h>
#include <stdlib.h>
#define put 0
#define get 1
#define run 2
int main () {
int ch;
printf("%s", "Please enter a command: ");
scanf("%d", ch);
switch (ch) {
case 0:
puts("You chose \"put\" as a command.");
break;
case 1:
puts("You chose \"get\" as a command.");
break;
case 2:
puts("You chose \"run\" as a command.");
break;
}
}
Ideally, when I scan for user input, I would like the user to be able to utilize the command's provided in the above #define statements. Therefore, the user is prompted for a value, put is input, and the program outputs the case 0. Is this possible with a switch()?
You'll need a function to convert the user input to your commands.
e.g.
int stringToCommand(char* cmd)
{
if (strcmp(cmd, "put") == 0)
return put;
...
}
Then you can use the #defines in the switch
int cmd = stringToCommand(userInput);
switch (cmd) {
case put:
puts("You chose \"put\" as a command.");
break;
...
Normally for this type of scenario I'd look at enums rather than relying on #defines.
Here is shown how the switch statement can be implemented.
#include <stdio.h>
#include <string.h>
int main(void)
{
const char * key_word[] = { "put", "get", "run" };
const size_t N = sizeof( key_word ) / sizeof( *key_word );
enum { PUT, GET, RUN };
char command[5];
printf( "Please enter a command: " );
fgets( command, sizeof( command ), stdin );
command[ strcspn( command, "\n" ) ] = '\0';
size_t i = 0;
while ( i < N && strcmp( command, key_word[i] ) != 0 ) i++;
/*
if ( i != N )
{
printf( "You chose \"%s\" as a command.\n", key_word[i] );
}
else
{
puts( "Invalid input." );
}
*/
switch ( i )
{
case PUT:
printf( "You chose \"%s\" as a command.\n", key_word[i] );
break;
case GET:
printf( "You chose \"%s\" as a command.\n", key_word[i] );
break;
case RUN:
printf( "You chose \"%s\" as a command.\n", key_word[i] );
break;
default:
puts( "Invalid input." );
break;
}
return 0;
}
The program output might look like
Please enter a command: get
You chose "get" as a command.
I have a task in university to write a C program which reads a file and counts the number of single and multi comments. The problem I have is that the second while() only reads the first line and so the returned comments are 0.
Previously I read the file character by character, but that's not the task requirement. Why does this program read only the first line and not the others?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fp;
int c, i = 0;
char path[256], ch, line[80];
unsigned int multi = 0;
unsigned int single = 0;
enum states {
PLAIN_TEXT,
SLASH,
STAR,
SINGLE_COMMENT,
MULTI_COMMENT,
QUOTES
} state = PLAIN_TEXT;
printf("Write file's name\n");
gets(path)
fp = fopen(path, "r");
if (!fp) {
// give an error message
} else {
while (fgets(line, sizeof(line), fp) != NULL) {
while (i < sizeof(line)) {
printf("%d.%c", i, line[i]);
switch (state) {
case PLAIN_TEXT:
switch (line[i]) {
case '/': i++;
state = SLASH;
break; // found a slash. In the next loop the switch argument will be SLASH
case '"': i++;
state = QUOTES;
break; // found a quote. Quoted text (there might be a '//' inside)
default: i++;
break; // found an ordinary character
}
break;
case QUOTES:
switch (line[i]) {
case '"': i++;
state = PLAIN_TEXT;
break; // Gets out the string;
case ' ':i++;
state = PLAIN_TEXT;
break;
default: i++;
state = QUOTES;
break; // Still a quoted text;
}
break;
case SLASH:
switch (line[i]) {
case '/': i++;
state = SINGLE_COMMENT;
break; // found a slash => a possible single comment found
case '*': i++;
state = MULTI_COMMENT;
break; // found a star => a possible multi comment found
default: i++;
state = PLAIN_TEXT;
break; // found an ordinary character
}
break;
case STAR:
switch (line[i]) {
case '/': i++;
state = PLAIN_TEXT;
multi++;
break; // Increments the multi comment and the next characher will be treated as a plain_taxt
default: i++;
state = MULTI_COMMENT;
break; // Still multi comment
}
break;
case SINGLE_COMMENT:
switch (line[i]) {
case '\n':i++;
state = PLAIN_TEXT;
single++;
break; // End of the single comment line. Increment the counter and the next character will be treated as a plain_text
default: i++;
break;
}
break;
case MULTI_COMMENT:
switch (line[i]) {
case '*': i++;
state = STAR;
break; // Found a multi comment. The next state will be star.
default: i++;
break;
}
break;
default: i++;
break;
}
}
}
fclose(fp);
printf("Single-comment : %8u\n", single);
printf("Multi-comment : %8u\n", multi);
}
return 0;
}
To enumerate the characters on the line, you must reinitialize i to 0 for each line and stop at the null terminator or at the newline character
I'm trying to create a simple program in c, where the user has to choose between several options:
char command = '1';
while(command!='0') {
printf("Menu:\n");
printf("1. First option\n");
printf("2. Second option\n");
printf("0. Exit\n");
printf("Choose: 0,1,2?: ");
command = getchar();
while(getchar()!='\n');
switch(command) {
case '0': break;
case '1': functionCall1(); break;
case '2': functionCall2(); break;
}
}
The problem with my code is, that every second time I enter 1,2 or 0, nothing happens, only the menu prints itself again. With the debugger I can see, that the value of command, after command = getchar() equals '', every second time. I thought that eating the newline character is enough?
Try my customized menu, I implemented it to make my life easier when I work with programs which contains multiple choices operations.
Menu is navigable (arrows:up, down, left, right), and for making a selection you only need to press enter key, menu orientation can be set vertically or horizontally, padding can be set to a group of items(childrens), child starting position, and update with delay.
Menu call example (vertically):
int response = menu("OPTIONS","[*]","->",
1,3,3,0,5,
"PROFILES","ACTIVITY","VIDEO","SOUND","GAMEPLAY");
The most important thing is because function implementation takes only 60 lines of code.
Menu implementation:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <windows.h>
// LXSoft
// mod: cui/menu_021
// stdarg.h -> used for variable list of arguments (va_list, va_start ...)
// windows.h -> used for Sleep function, for *nix use unistd.h
typedef unsigned short int usint_t;
// Menu function prototype
int menu(char* name, char* prefix, char* cursor, usint_t orientation,
usint_t padding, usint_t start_pos, usint_t delay,
usint_t num_childs, ...);
int main()
{
int response = menu("OPTIONS","[*]","->",1,3,3,0,5,
"PROFILES","ACTIVITY","VIDEO","SOUND","GAMEPLAY");
switch(response)
{
case 1:
// doSomethingFoo1();
break;
case 2:
//doSomethingFoo2();
break;
/*
* .
* .
* .
* case n:
* break;
*/
}
printf("\nYour choice is: %d", response);
return 0;
}
// Menu implementation
int menu
(
char *name, // Menu name (eg.: OPTIONS)
char *prefix, // Menu prefix (eg.: [*])
char *cursor, // Menu cursor (eg.: ->)
usint_t orient, /*
* Menu orientation vertical or horzontal.
* 0 or false for horizontal
* 1 or true for vertical
*/
usint_t padding, // Menu childrens padding (eg.: 3)
usint_t start_pos, // Menu set active child (eg.: 1)
usint_t delay, // Menu children switch delay
usint_t childs, // Number of childrens
... /*
* Variable list of arguments char* type.
* Name of the childrens.
*/
)
{
va_list args;
int tmp=0,pos;
char chr;
usint_t opt=start_pos;
char* format=malloc
(
(
strlen(name)+strlen(prefix)+strlen(cursor)+
3+ /* menu suffix (1 byte) and backspace (2 bytes) */
(2*childs)+ /* newline (2 bytes) times childs */
(padding*childs)+ /* number of spaces times childs */
childs*15 /* children name maxlen (15 bytes) times childs*/
)*sizeof(char)
);
do
{
if(tmp!=0)chr=getch();
if(chr==0x48||chr==0x4B)
(opt>1&&opt!=1)?opt--:(opt=childs);
else if(chr==0x50||chr==0x4D)
(opt>=1&&opt!=childs)?opt++:(opt=1);
else {/* do nothing at this time*/}
strcpy(format,"");
strcat(format,prefix);
strcat(format,name);
strcat(format,":");
va_start(args,childs);
for (tmp=1;tmp<=childs;tmp++)
{
(orient)?strcat(format,"\n"):0;
pos=padding;
while((pos--)>0) strcat(format," ");
if(tmp==opt)
{
strcat(format,"\b");
strcat(format,cursor);
}
strcat(format,va_arg(args,char*));
}
/*if(tmp!=childs)
{
fprintf(stderr,"%s: recieved NULL pointer argument,"
" child not named", __func__);
return -1;
}*/
Sleep(delay);
system("cls");
printf(format);
va_end(args);
}while((chr=getch())!=0x0D);
return opt;
}
May be you should try to use int x as a key to use a desirable command, may be like that:
while(x != 0)
{
scanf("%d", &x);
switch (x)
{
printf("input '2' to...\n");
printf("input '3' to...\n");
printf("input '4' to...\n");
printf("input '5' to...\n");
printf("input '6' to...\n");
case 1:
head = Enqueue(head);
break;
case 2:
head1 = spisokMagazinovScenoiMensheiZadannoi(head, head1);
break;
case 3:
head1 = udalenieElementa(head1);
break;
case 4:
head1 = addNewMagazin(head1);
break;
case 5:
head1 = addNewMagazin(head1);
break;
case 6:
printToTheFile(head);
break;
}
}
I used it in my previous homework. Hope it will be usefull for you
it's my exaple of func menu.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <windows.h>
int menu(char s[][80],int kolop){
int pos = 0,push = 0,i,flag = 0;
printf("MENU:\n>");
puts(s[0]);
for(i = 1;i < kolop;i++){
printf(" ");
puts(s[i]);
}
printf("Enter 5 to move the cursor down 8 to the top(Press ENTER to end)\n");
do{
if(flag == 1)
printf("Error try to press 5,8 or ENTER\n");
push = getch();
flag = 1;
}
while(push != 56 && push != 53 && push != 13);
flag = 0;
system("cls");
while(push != 13){
if(push == 53){
puts("MENU:");
for(i = 0;i < kolop;i++){
if(i == pos + 1 && flag == 0){
printf(">");
puts(s[i]);
flag = 1;
pos++;
}
else{
printf(" ");
puts(s[i]);
}
}
}
if(push == 56){
puts("MENU:");
for(i = 0;i < kolop;i++){
if(i == pos - 1 && flag == 0){
printf(">");
puts(s[i]);
flag = 1;
pos--;
}
else{
printf(" ");
puts(s[i]);
}
}
}
_flushall();
printf("Enter 5 to move the cursor down 8 to the top(Press ENTER to end)\n");
flag = 0;
do{
if(flag == 1)
printf("Error try to press 5,8 or ENTER\n");
push = getch();
flag = 1;
}
while(push != 56 && push != 53 && push != 13);
flag = 0;
system("cls");
}
pos++;
return pos;
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
char s[][80] = {"1","2","3","4","5","6","7"};
int i,pos = 0,push,flag = 0;
pos = menu(s,7);
printf("%d",pos);
//system("cls");
return 0;
}