I am trying to make a menu with the options to compress a text inputted by the user and then store that value to be extracted in the extract menu option.
The issue lies in that it seems like the code isn't following the void statements, for example
case 1: compress();//compress statement
It seems to only get the printf statement in the void compress(void) and not the scanf, which it then follows with the loop of the menu.
Any solutions?
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
void menu(void);
void compress(void);
void extract(void);
int main(void)
{
menu();
return 0;
}
void menu(void)
{
int choice;
do
{
printf("Menu\n\n");
printf("1. Compress Text\n");
printf("2. Extract Text\n");
printf("3. Exit\n");
scanf_s("%d", &choice);
switch (choice)
{
case 1: compress();//compress statement
break;
case 2: extract();//extract statement
break;
case 3: printf("Ciao\n");
exit(0);
break;
default: printf("Invalid Entry. Try again\n");
break;
}
} while (choice != 3);
}
void compress(void) {
printf("\n-------------------------\n");
printf(" COMPRESS ");
printf("\n-------------------------\n");
printf("\nPlease enter a word/sentence to be compressed:\n");
char txt[200];
scanf_s("%c", &txt);
printf("\nYour word/sentence is %c", txt, "\n");
char comp = strlen(txt);
int mask[200]{};
for (int i = 0; i < comp; i) //loop until all leters are masked
{
mask[i] = i 127;
printf("\nYour compressed word/sentence is %c ", mask[i]);
}
return;
}
void extract(void) {
printf("\n-------------------------\n");
printf(" EXTRACT ");
printf("\n-------------------------\n");
return;
}
CodePudding user response:
You are scanning only one single character, and as "%c"
doesn't skip white-space this is the newline character terminating the previous input.
You instead want to read in a string, and to be on the safe side you should add the maximum length to read to: "9s"
(note: one less than array size to leave space for the terminating null character):
scanf_s("9s", txt);
Note, too, that as txt
is an array it decays to a pointer automatically when being passed to a function (see above); taking the address of (&txt
) produces a pointer with the same value, but of a different type: char(*)[200]
. This pointer is not compatible to neither %c
nor %s
format specifier, thus you actually produce *undefined behaviour!
Note, too, that scanf_s
(any function from scanf
family) will stop reading at the first whitespace – a sentence might, though contain multiple words separated by whitespace. You'd just read the first one of them, though. So you might want to drop scanf
for this input entirely in favour of e.g. fgets
:
fgets(txt, sizeof(txt), stdin);
Note, here, too, that the previous scanf("%d", ...)
did not consume the terminating newline, so you'll need to ignore that, e.g. by a preceding call to getchar
.
Crediting this last point to Jonathan Leffler who hinted to in his comment to the question)