Home > Mobile >  Cannot execute int function in menu
Cannot execute int function in menu

Time:10-22

I wrote program which use menu to execute function.

#include <iostream>
#include<conio.h>
#include <stdio.h>
#include <cstring>

using namespace std;

int menu();
void zad1();
void zad2();


int main(){
    switch(menu()){
        case 1: zad1();break;
        case 2: zad1();break;

        default: cout<<"blank";
    };
    getch();
    return 0;
}

int menu(){
    cout<<"Menu\n\n";
    cout<<"Zad.1\nZad.2\n";
    int wybor;
    cin>>wybor;
    return wybor;
}

int encryption(){
    char string[256];
    int i = 0;
    int key = 3;
    const int num_letters = 26;

    printf("Enter the string you want encrypted\n");
    fgets(string, sizeof(string), stdin);

    for (i = 0; i < strlen(string); i  ) {
        if (string[i] >= 'a' && string[i] <= 'z') {
            string[i] = 'a'   (string[i] - 'a'   key) % num_letters;
        }
        else if (string[i] >= 'A' && string[i] <= 'Z') {
            string[i] = 'A'   (string[i] - 'A'   key) % num_letters;
        }
    }
    printf("Encrypted: %s\n", string);
    return 0;
}

void zad1(){
    encryption();
}

The only thing is I my output is not working properly - it shows the menu, I can type number (1-2) to choose function to execute and all I get from function "encryption" is:

Enter the string you want encrypted
Encrypted:

and that's all - I can't type character. What am I missing? I used the menu before and everything worked properly.

CodePudding user response:

After this input

cin>>wybor;

the input buffer contains the new line character '\n'.

So the next call of fgets

printf("Enter the string you want encrypted\n");
fgets(string, sizeof(string), stdin);

reads an empty string that contains only this new line character.

You need to clear the buffer before calling the function as for example

while ( getchar() != '\n' );
printf("Enter the string you want encrypted\n");
fgets(string, sizeof(string), stdin);

Or instead of the C function fgets you could use the C member function ignore for the object std::cin together with the function getline. . Also it seems here is a typo

 case 2: zad1();break;

You should write

 case 2: zad2();break;

Pay attention to that in fact your program is a C program. You are not using C features except the operator << for the output stream in the function menu. Using C stream functions and C stream functions together is a bad idea.

  • Related