Vigener cipher, looping the key - c

I would like to ask your help about my program. It will be a vigenere-cipher solution, but I have to encrypt it from a file.
My problem is that I can't loop my keyword for the message length.
There are the tasks
Ask the message you want to translate,maximum 255 character
I have to transform the message to unaccented,upper case and without spaces
Than print it to the screen.
Ask the key, maximum five character and the same transformation.
I have to loop the key for the lenght of the message. than print it to the screen. Now that's what I can't do.
Can somebody please help me in it?
#include <stdio.h>
#include <ctype.h>
#define MAX 256
#define KMAX 6
void mess(void){
char message[MAX];
int j,i,k=0;
char big[]={"ÁÉÍÓÖŐÚÜŰ"}, small[]={"áéíóöőúüű"}, english[]={"aeiooouuu"};
printf("Please give the message you want to enrypt! Maximum %d character: ",MAX-1); // 1.
fgets(message,MAX,stdin); // 2.
for(i=0;message[i];i++){
j=0;
while(small[j] && (message[i]!=small[j] && message[i]!=big[j])){
j++;
}
if(small[j]){
message[i]=english[j];
}
if(isalpha(message[i])){
message[k]=toupper(message[i]); k++;
}
}
message[k]='\0';
printf("\nThe clean message is: %s\n\n",message);
}
void keyword(void){ // 3.
char key[KMAX];
int j,i,k=0;
char big[]={"ÁÉÍÓÖŐÚÜŰ"}, small[]={"áéíóöőúüű"}, english[]={"aeiooouuu"};
printf("Please give the key!Maximum %d character\n",KMAX-1);
fgets(key,KMAX,stdin);
for(i=0;key[i];i++){
j=0;
while(small[j] && (key[i]!=small[j] && key[i]!=big[j])){
j++;
}
if(small[j]){
key[i]=english[j];
}
if(isalpha(key[i])){
key[k]=toupper(key[i]); k++;
}
}
key[k]='\0';
printf("\nThe clean key is: %s\n\n",key);
}
void loop() //4.
{
}
int main(void){ // main
system("CHCP 1250");
system("CLS");
mess();
keyword();
loop();
return 0;
}

Related

C: Function not behaving as intended when called by "if" statement

I'm a C beginner and am working on a program that registers flights using structs. Each flight has a code that must follow a certain structure: FLI-XXXX, X being integers. I'd like to use the integers part of the code later on, so I thought the best way to scan for it was using both fgets and scanf. After validating the code using auxiliary variables, I would later write it to the flights struct. However, I'm stuck at the validating part.
The problem is, whenever I call the function that validates a code (opt1) inside an if statement, it runs twice and only works as intended the second time around. Here's my code:
#include <stdio.h>
#include <string.h>
typedef struct
{
int num;
char code[5];
}fl;
fl flight[9999];
int Valid(char a[], int b)
{
if((strlen(a) != 4) || (b<0 || b>9999)){
return 0;
}
else if(a[0] !='F' || a[1] !='L' || a[2] !='I' || a[3] != '-'){
return 0;
}
return 1;
}
void opt1(fl a[]){
char tempCode[5];
int tempNum;
do
{
puts("Insert code:");
fgets(tempCode, 5, stdin);
scanf("%d", &tempNum);
puts("");
if (Valid(tempCode, tempNum))
{
printf("Flight %s%d registered. \n", tempCode, tempNum);
}
else
{
puts("Flight # invalid.");
}
} while (Valid(tempCode, tempNum)==0);
}
int main() {
int opt;
//calling opt1 works as intended
opt1(flight);
//calling inside if statement runs opt1() twice, only the second time as intended
scanf("%d", &opt);
if(opt==1){
opt1(flight);
}
return 0;
}
And here's an input:
FLI-1234
1
FLI-1234
That returns:
Flight FLI-1234 registered.
Insert code:
Flight # invalid.
Insert code:
Flight FLI-1234 registered.
I'm not sure why this is happening. Can anyone guide me in the right direction, please? Thank you.

My C code aint stop and i can't end the loop

What am I doing wrong? My code keeps in loop and n goes minus. It was supposed to return 0; at 0.Also whatever I do it starts with 3-2-1-0 even I type "2" it still keeps doing it 3-2-1-0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
static const char PSWRD[]="1234";
char p[6];
int n=3, y;
printf("Hos geldiniz");
do{
printf("\n\nOgrenci_ID:Elif");
fflush(stdout);
printf("\nSifre:");
scanf("%s", &p);
fflush(stdout);
y=strcmp(p, PSWRD);
if(y==0){
printf("\nGiris Basarili"); `//succesfull login`
return 0;
}else {
printf("Yanlis Sifre, tekrar deneyiniz", 3-n); //wrong password try again
printf("\nKalan hakkiniz ");
printf("%d\n", n);
getchar();
n--;}
if(n<1){
printf("\nHesabiniz bloke oldu");
return 0;
// that means you use all your chance and now you're blocked but my code aint stop here and n goes minus
}
// I am not exactly sure about "3"
//Also what ever i do it starts with 3-2-1-0 even i type "2" it's still keep doing it 3-2-1-0
}while (n<=3);
return 0;
}
while (n<=3);
doesn't agree with
n--;
You seem to want
while (n>0);
Its working for me!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
static const char PSWRD[]="1234";
char p[6];
int n=3, y;
printf("Welcome");
do{
printf("\n\nStudent_ID:Elif");
fflush(stdout);
printf("\nPassword:");
scanf("%s", p);
fflush(stdout);
y=strcmp(p, PSWRD);
if(y==0){
printf("\nSucessfull Login\n"); //succesfull login
return 0;
}else{
n--;
printf("\nWrong password, try again: "); //wrong password try again
printf("\nRemaining attempts ");
printf("%d\n", n);
getchar();
}
if(n<1){
printf("\nYour account has been blocked\n");
return 0;
}
}while (n>0);
}
When user introduces wrong password, you have more 2 tries and if you enter the password wrong on thats 2 tries program ends! But if you insert it right program makes login, so works fine
In your code, there is no increment of 'n', so the loop keeps going (because n is always smaller than 3). I'm not too sure of what you're trying to do, but you need to change your 'while' condition or statements of 'n' inside the loop.
Currently the loop keeps running forever:
When n=3 - > 3<=3 is true.
When n=2 - > 2<=3 is true.
Etc.
The only way it's going to end is when n decrements until it is equal to the absolute minimum value of an integer which is -2,147,483,648, then it will decrement one more time and change to 2,147,483,647 and the loop will end.
Use printf to watch the value of n, and you will quickly observe that your condition for the do...while loop is incorrect.
However, note the conditional, if(n<=0) with return.
Provide a minimal reproducible example, such as below...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int login(char* PSWRD)
{
int n=3, y;
char p[100+20];
printf("Hos geldiniz");
do{
printf("\nSifre:");
scanf("%100s", p); // limit input size, use p, not &p
if( 0 == strcmp(p, PSWRD) ) {
printf("\nsuccess!");
return 0;
}
printf("Yanlis Sifre, tekrar deneyiniz"); //wrong password try again
n--;
if(n<=0)
{
printf("\nHesabiniz bloke oldu");
return -1;
}
printf("n=%d\n",n); // print current n
} while (n<=3); // this should be (n>0)
return -1;
}
int main()
{
char* PASSWD = "password";
int result;
if( 0 > login(PASSWD) ) {
printf("\nfailed!\n");
exit(1);
}
printf("\nsuccess!\n");
// continue processing here
}
Caveat: Make sure you limit input size to avoid buffer overflow
Read no more than size of string with scanf()

how to implement countdown timer in milliseconds to answer a question. If timer runs out, loop breaks

Okay, so I am working on a project right now, and the project is to create a game. Here is the concept below:
Please press any key to begin!
Press the ‘h’ key!
You have 2500 milliseconds to respond!
Press the ‘c’ key!
You have 2400 milliseconds to respond!
Press the ‘k’ key!
You have 2300 milliseconds to respond!
Wrong key! :(
You lose!
You made it through 3 rounds!
Here is the code I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
/*----------------------------------------------------------------------------
- Prototypes -
-----------------------------------------------------------------------------*/
char random1 ();
int cmpChar(char rand2, char user1);
/*----------------------------------------------------------------------------
- Implementation -
-----------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
srand(time(NULL)); /* This will ensure a random game each time. */
time_t cdt;
time(&cdt);
ctime(&cdt);
printf("%s\n", ctime(&cdt));
char ans, randChar;
int gameCont = 1;
int score = 0;
printf("This is a Bop-It Game!\n");
printf("\nPress any key to start\n");
getch();
int i = 2600;
while(gameCont == 1){
randChar = random1();
printf("press the '%c' key!\n", randChar);
ans = getch();
gameCont = cmpChar(randChar, ans);
if (gameCont == 1){
score++;
i -= 100;
printf("You have %d milliseconds to respond!\n", i);
}
}
printf("Your score was %d!\n", score);
return 0;
}
char random1 (){
char randInput;
randInput = (rand()%(122-90)+90);
return randInput;
}
int cmpChar(char rand2, char user1){
if (user1 == rand2){
return 1;
}
if (user1 != rand2){
printf("That is incorrect\n");}
else{
return 0;
}
}
If you can see, I implemented a code that kind of mimics the countdown millisecond thing, but it doesnt actually use a timer, it just uses a loop and print statements.
Im on windows OS, and am trying to use #include <sys/time.h> to create a way to implement a timer, and also have it decrease by 100 milliseconds after each iteration.
If you can help with the whole implementation, great, otherwise just a nudge in the right direction would be greatly appreciated.

Why this postfix input calculator in c using stack of array doesn;t work?

I am learning data structures and as I go through I needed to make a postfix input calculator in c.I wanted to make it using stack and stack of array.I wrote some code but it is not giving output instead it gives the first word i input in it.If I dont take input and give value in declaration of string this works but if I ask for input then it doesnt work.And i also tried to print strlength after the scanf it even if my input is 17 length it only prints 1.scan f is not working correctly or strlen is not working correctly.My code is :-
#include <stdio.h>
#include <string.h>
#include "stack_forpostfix.h"
int postfix(char *exp);
int isoperator1(char b);
int isnumericdigit1(char c);
int doevaluation(int oper1,char optr,int oper2);
int main(){
char *exp1;
int a;
printf("Enter the postfix expresssion\n");/*if we dont ask and put input in declaration the code works perfect,because if we ask the strlen is not working*/
scanf("%s",exp1); //2 3 * 5 4 * + 9 -
printf(" , %d , ",strlen(exp1));
a=postfix(exp1);
printf("%d\n",a);
}
int postfix(char *exp){
for(int i=0;i<strlen(exp);i++){
if(exp[i]==' ' || exp[i]==','){
continue;
}
else if(isoperator1(exp[i])){
int op2=gettop();
pop();
int op1=gettop();
pop();
int result=doevaluation(op1,exp[i],op2);
push(result);
}
else if(isnumericdigit1(exp[i])){
int oper=0;
while(i<strlen(exp) && isnumericdigit1(exp[i])){
oper=(oper*10)+(exp[i]-'0');
i++;
} //since i++ is there if no i-- exp[i] will escape one further
i--;
push(oper);
}
}
return gettop();
}
int isnumericdigit1(char c){
if (c>='0' && c<='9'){
return 1;
}
else return 0;
}
int isoperator1(char b){
if(b=='+'||b=='-'||b=='*'||b=='/'){
return 1;
}
else {
return 0;
}
}
int doevaluation(int oper1,char optr,int oper2){
if(optr=='+'){
return oper1+oper2;
}else if (optr=='-'){
return oper1-oper2;
}else if (optr=='*'){
return oper1*oper2;
}else if (optr=='/'){
return oper1/oper2;
}else {
printf("not valid");
return -1;
}
}
And my header file(stack_forpostfix.h) code is :-
#ifndef stackyfix
#define stackyfix
#define maxsize 111
int a[maxsize];
int top=-1;
void push(int r){
top++;
a[top]=r;
}
void pop(){
top--;
}
int gettop(){
return a[top];
}
#endif
scanf("%s",exp1);
Will stop reading when it encountered to whitespace characters.
You should use fgets() instead.
Also, do not forget to allocate buffer for reading the expression.
char exp1[102400]; // believing that huge expression won't come
fgets(exp1, sizeof(exp1), stdin);
Also note that
printf(" , %d , ",strlen(exp1));
will invoke undefined behavior for type mismatch: %d expects int while strlen() returns size_t.
The format type specifier to print size_t is %zu.
If your environment doesn't support %zu, you should cast the return value to int before passing it to %d.
In infix to postfix function, in place of str[i]=gettop(); there should be str[j]=gettop() so the expression entered inside the brackets can be pprocessed. Also add this piece of code after fgets to remove the '\n' that fgets may append.
fgets(b,sizeof(b),stdin);
for(int i=0;b[i]!='\0';i++){ // removes \n added by fgets
if(b[i]=='\0'){
if(b[i-1]=='\n'){
b[i-1]='\0';
}
}
}

Testing length of inputed message with old message

I'm working on a program that asks me to enter a new message and replacing the old one, but I have to test if the message is longer than the last one. I would like to get answer that is similar to my program because this is a lesson I'm learning right now. It asks me to input size of new char, but when I test it, it takes my set size for testing.
#include <stdio.h>
#include <stdlib.h>
void editedMessage(char* nmessage, int size){
char newMessage[];
printf("Enter a new message!\n");
gets_s(newMessage, sizeof(newMessage));
if (size > sizeof(newMessage)){
for (int i = 0; i < sizeof(newMessage); i++){
nmessage[i] = newMessage[i];
}
}
else {
printf("New message is too long.\n\n");
}
}
void main(){
char message[] = "This is some message!";
printf("Old message\n%s\n\n", message);
editedMessage(message, sizeof(message));
printf("New message\n\n%s\n\n", message);
}
EDIT: I edited next code but now says 'stack around the variable 'message' was corrupted'
char newMessage[256];
printf("Enter a new message!\n");
gets_s(newMessage, sizeof(newMessage));
int len = strlen(newMessage);
if (size > len){
for (int i = 0; i < sizeof(newMessage); i++){
nmessage[i] = newMessage[i];
}
}
I changed the return type of editedMessage to char* and cut down it arguments.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 1000
char* editedMessage(char* oldMessage){
char newMessage[MAX_LENGTH];
printf("Enter a new message : ");
fgets(newMessage,MAX_LENGTH,stdin);
if (strlen(newMessage)<= strlen(oldMessage)){
strcpy(oldMessage,newMessage);
}
else {
printf("New message is too long.\n\n");
}
return oldMessage; // In fact the value of oldMessage should have been changed if the new message is shorter in length
}
void main(){
char message[MAX_LENGTH] = "This is some message!";
printf("Old message : %s\n", message);
editedMessage(message);
/* Since we are dealing with pointers, note that I am not catching any
* return values here. In essence any changes made to message in the
* editedMessage function is automatically effective in the main
* function.
*/
printf("New message :%s\n", message);
}

Resources