C game does not finish - c

i wrote a simple barbut game in long way.
I want to learn something, if get in 42. line; when the game over, it doesnt go to 84. line.
If the game doesnt get in 42. line, when game is overgoes to 84. line.
int main() {
setlocale(LC_ALL, "Turkish");
int zar1 = 0;
int zar2 = 0;
int i = 1;
int a = 1;
int toplamzar = 0;
int oyuncununzari = 0;
while (i == 1) {
srand(time(NULL));
zar1 = 1 + (rand() % 6);
zar2 = 1 + (rand() % 6);
toplamzar = zar1 + zar2;
printf("\n****ZAR 1: %d \n****ZAR 2: %d\n", zar1, zar2);
switch (toplamzar) {
case 7: case 11:
printf("%d attınız ve kazandınız.", toplamzar);
break;
case 2: case 3: case 12:
printf("%d attınız ve kaybettiniz.", toplamzar);
break;
case 4: case 5: case 6: case 8: case 9: case 10: {
printf("%d sayısı sizin sayınız.", toplamzar);
oyuncununzari = toplamzar;
toplamzar = -2;
printf("\nZar atın:");
scanf("%d", &a);
while (toplamzar != oyuncununzari || toplamzar != 7) {
while (a == 1) {
zar1 = 1 + rand() % 6;
zar2 = 1 + rand() % 6;
toplamzar = zar1 + zar2;
printf("\n****ZAR 1: %d \n****ZAR 2: %d\n", zar1, zar2);
if (toplamzar == oyuncununzari) {
printf("%d attınız, kazandınız.", toplamzar);
a = 0;
}
else
if (toplamzar == 7) {
printf("%d attınız, kaybettiniz.", toplamzar);
a = 0;
}
else
if (toplamzar != 7 && toplamzar != oyuncununzari) {
scanf("%d", &a);
}
}
}
break;
}
}
printf("\nTekrar oynamak ister misiniz?");
scanf("%d", &i);
}
return 0;
}

You need to change line :
while (toplamzar != oyuncununzari || toplamzar != 7)
to :
while ( (toplamzar != oyuncununzari) && (toplamzar != 7) )
so that the loop executes when both conditions are true. Right now it executes even if just one of them is true.

Related

Making a digital clock in C

I am trying to make a built-in digital clock in a C program.
This is the code I used:
int wmain(void) {
time_t t;
t = time(NULL);
struct tm tm = *localtime(&t);
int m;
printf(" %d ", tm.tm_mday);
m = tm.tm_mon+1;
switch(m)
{
case 1:
printf("Jan, ");
break;
case 2:
printf("Feb, ");
break;
case 3:
printf("Mar, ");
break;
case 4:
printf("Apr, ");
break;
case 5:
printf("May, ");
break;
case 6:
printf("June, ");
break;
case 7:
printf("July, ");
break;
case 8:
printf("Aug, ");
break;
case 9:
printf("Sep, ");
break;
case 10:
printf("Oct, ");
break;
case 11:
printf("Nov, ");
break;
case 12:
printf("Dec, ");
break;
}
printf("%d", tm.tm_year+1900);
printf("\n ");
if(tm.tm_hour>=12)
{
if(tm.tm_hour==12)
printf("12");
else
printf("%d", tm.tm_hour-12);
printf(":%d PM\n", tm.tm_min);
}
else
printf("%d:%d AM", tm.tm_hour, tm.tm_min);
//getch();
return 0;
}
The problem with this code is that you have to refresh every minute in order for the clock to update.
I have another code here:
void clock()
{
int h = 2, m = 41, s = 12;
int d = 1000;
while(1){
s++;
if (s > 59){
m++;
s = 0;
}
if (m > 59){
h++;
m = 0;
}
if(h>12){
h = 1;
}
printf("%02d : %02d : %02d", h, m, s);
Sleep(d);
system("cls");
//menu();
}
printf("\n\n");
}
but this code goes into an infinite loop and doesn't display anything else but the clock.
So, how can I update the seconds in the clock without going into infinite loop?
#include <stdio.h>
#include <conio.h>
#include <Windows.h>
DWORD WINAPI digclock()
{
int h = 2, m = 41, s = 12;
int d = 1000;
while (1) {
s++;
if (s > 59) {
m++;
s = 0;
}
if (m > 59) {
h++;
m = 0;
}
if (h > 12) {
h = 1;
}
printf("%02d : %02d : %02d", h, m, s);
Sleep(d);
}
printf("\n\n");
return;
}
void main()
{
HANDLE clockThread = CreateThread(NULL, 0, digclock, NULL, 0, NULL);
if (clockThread == INVALID_HANDLE_VALUE) {
printf("Error creating thread.\n");
}
while(1)
{
printf("main continue without block \n");
Sleep(500);
}
return;
}
Try above code, basically your clock should be running in separate thread. create thread API may differ in your environment.

Problem with input and output to and from .txt file

My homework is to calculate the resistance in Ohms of a resistor give a text file with information about the resistor. Using this text file, I calculate the resistance and print it to another text file. When I run this code I get a debug error "Run-Time check failure #3-T" and no output to the file. Can you tell me where I am going wrong?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<math.h>
int col_to_num(char color, int choice) {
int num;
switch (color) {
case 'B':if (choice == 1) num = 0;
else if (choice == 2) num = 1;
else if (choice == 3)num = 6;
case 'b':if (choice == 1) num = 0;
else if (choice == 2) num = 1;
else if (choice == 3)num = 6;
case 'G':if (choice == 1) num = 5;
else if (choice == 2) num = 8;
else if (choice == 3)num = -1;
case 'g':if (choice == 1) num = 5;
else if (choice == 2) num = 8;
else if (choice == 3)num = -1;
case 'R':num = 2;
case 'r':num = 2;
case 'O':num = 3;
case 'o':num = 3;
case 'Y':num = 4;
case 'y':num = 4;
case 'V':num = 7;
case 'v':num = 7;
case 'W':num = 9;
case 'w':num = 9;
case 'S':num = 10;
case 's':num = 10;
}
return num;
}
int main() {
double resistance, thirdband;
char color1, color2, color3;
int val1, val2, val3;
FILE *inp, *outp;
inp = fopen("resistorcolor.txt", "r");
outp = fopen("resistorvalue.txt", "w");
if (inp == NULL) {
printf("The input file does not exist\n");
}
else {
while (fscanf(inp, "%c %d %c %d %c %d%*c", &color1, &val1, &color2, &val2, &color3, &val3) != EOF) {
if (col_to_num(color3, val3) == -1)thirdband = .01;
if (col_to_num(color3, val3) == 10)thirdband = .01;
if (col_to_num(color3, val3) == 0)thirdband = 1;
if (col_to_num(color3, val3) == 1)thirdband = 10;
if (col_to_num(color3, val3) == 2)thirdband = 100;
if (col_to_num(color3, val3) == 3)thirdband = 1000;
if (col_to_num(color3, val3) == 4)thirdband = 10000;
if (col_to_num(color3, val3) == 5)thirdband = 100000;
if (col_to_num(color3, val3) == 6)thirdband = 1000000;
resistance = ((col_to_num(color1, val1) * 10) + col_to_num(color2, val2))*thirdband;
fprintf(outp, "%.2lf Ohm", resistance);
thirdband = 0;
}
fclose(outp);
}
return 0;
}
Run-Time check failure #3 mean something was used without being initialized. There is more information which you are not seeing. The error message should be "Run-Time check failure #3: The variable 'XXX' is being used without being initialized", where XXX is a variable in your code.
In any case you have a lot of uninitialized variables, those should be initialized to some default value:
double resistance = 0.0, thirdband = 0.0;
char color1 = 0, color2 = 0, color3 = 0;
int val1 = 0, val2 = 0, val3 = 0;
FILE *inp = nullptr, *outp = nullptr;
and for the function:
int col_to_num(char color, int choice) {
int num = -1;
Most likely it is int num from the col_to_num function, which will never hit a case if you didn't pass in one of those values. You need to break to exit the switch statement, usually after your condition is hit, however you can group cases together by not breaking allowing you to easily do the same action for different cases. Think of it as falling through starting at the case that is matched. You also need a default case to handle if no cases are matched like this:
int col_to_num(char color, int choice) {
int num = -1;
switch (color) {
case 'B':
case 'b':
if (choice == 1) num = 0;
else if (choice == 2) num = 1;
else if (choice == 3)num = 6;
break;
case 'G':
case 'g':
if (choice == 1) num = 5;
else if (choice == 2) num = 8;
else if (choice == 3)num = -1;
break;
case 'R':
case 'r':
num = 2;
break;
case 'O':
case 'o':
num = 3;
break;
case 'Y':
case 'y':
num = 4;
break;
case 'V':
case 'v':
num = 7;
break;
case 'W':
case 'w':
num = 9;
break;
case 'S':
case 's':
num = 10;
break;
default:
printf("Invalid input: %c\n", color);
}
return num;
}
perhaps you got a wrong understanding of switch case. You need to include break statement after every case if not added, all the cases will run whatever the input may be. And second thing is, you have to initialize the variables before using them. Hope that helps. Cheers !! Feel free to ask any doubts.

Why does it say 'expected declaration specifiers before 'main''

first of all, I understand mostly everything in this program that I copied from this book.
second, i just wanted to see if it worked ,
the only problem is that it says 'expected declaration specifiers before 'main''
and i don't know what it means
ps this is a really long program (300+ lines)
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
int analyzeHand(int ranksinHand[], int suitsinHand[]);
main()
{
int bet;
int bank = 100;
int i;
int cardRank [5];
int cardSuit [5];
int finalRank[5];
int finalSuit[5];
int ranksinhand[13];
int suitsinhand[4];
int winnings;
time_t t;
char suit, rank, stillPlay;
printGreeting();
do{
bet = getBet();
srand(time(&t));
getFirstHand(cardRank, cardSuit);
printf("Your five cards: \n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(cardsSuit[i]);
rank = getRank(cardRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
for (i=0; i < 4; i++)
{
suitsinHand[i] = 0;
}
for (i=0; i < 13; i++)
{
ranksinHand[i] = 0;
}
getFinalHand(cardRank, cardSuit, finalRank, finalSuit, ranksinHand,
suitsinHand);
printf("Your five final cards:\n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(finalSuit[i]);
rank = getRank(finalRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
winnings = analyzeHand(ranksinHand, suitsinHand);
printf("You won %d!\n\n", bet*winnings);
bank = bank - bet + (bet*winnings)
printf("\n\nYour bank is now %d.\n\n", bank);
printf("Want to play again? ");
scanf(" %c", &stillPlay);
}while (toupper(stillPlay) == 'Y');
return;
}
/*************************************************************************/
void printGreeting();
{
printf("**********************************************************\n\n");
printf("\n\n\tWelcome to the Absolute Beginner's Casino\n\n");
printf("\tHome of the Video Draw Poker");
printf("**********************************************************\n\n");
printf("Here are the rules\n");
printf("You start with 100 credits, and you make a bet from");
printf("1 to 5 credits.\n");
printf("You are dealt 5 cards, and then you choose which ");
printf("cards to keep");
printf("or discard\n");
printf("You want to make the best possible hand.\n");
printf("\nHere is the table for winnings (assuming a ");
printf("bet of 1 credit):");
printf("\nPair \t\t\t\t1 credit");
printf("\nTwo pairs\t\t\t2 credits");
printf("\nThree of a kind\t\t\t3 credits");
printf("\nStraight \t\t\t4 credits");
printf("Flush\t\t\t\t5 credits");
printf("Full House\t\t\t8 credits");
printf("Four of a Kind\t\t\t10 credits");
printf("Straight Flush\t\t\t20 credits");
printf("\n\nHave fun!!\n\n");
}
void getFirstHand(int cardRank[], int cardSuit[]);
{
int i,j;
int carDup;
for(i=0; i < 5; i++)
{
carDup = 0;
do{
cardRank[i] = (rand() % 13);
cardSuit[i] = (rand() % 4);
for (j=0; j < i; j++)
{
if ((cardRank[i] == cardRank[j] &&
cardSuit[i] == cardSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1;);
}
}
char getSuit(int suit)
{
switch
{
case 0:
return('C');
case 1:
return('D');
case 2:
return('H');
case 3:
return('S');
}
}
char getRank(int rank)
{
switch (rank)
{
case 0:
return('A');
case 1:
return('2');
case 2:
return('3');
case 3:
return('4');
case 4:
return('5');
case 5:
return('6');
case 6:
return('7');
case 7;
return('8');
case 8:
return('9');
case 9:
return('T');
case 10:
return('J');
case 11:
return('Q');
case 12:
return('K');
}
}
int getBet()
{
int bet;
do
{
printf("How much do you want to bet?(Enter a number");
printf("from 1 to 5, or 0 to quit the game): ");
scanf(" %d", &bet);
if (bet >= 1 && bet <= 5)
{
return(bet);
}
else if (bet == 0)
{
exit(1);
}
else
{
printf("\n\nPlease enter a bet from 1-5 or ");
printf("0 to quit the game\n\n");
}
}while ((bet < 0) || (bet > 5));
}
int analyzeHand(int ranksinHand[], int suitsinHand[])
{
int num_consec = 0;
int i, rank, suit;
int straight = FALSE;
int flush = FALSE;
int four = FALSE;
int three = FALSE;
int pairs = 0;
for (suit = 0; suit < 4; suit++)
if (suitsinHand[suit] == 5)
flush = TRUE;
rank = 0;
while (ranksinHand[rank] == 0)
rank++;
for (; rank < 13 && ranksinHand[rank]; rank++)
num_consec++;
if(num_consec == 5) {
straight = TRUE;
}
for (rank = 0; rank < 13; rank++){
if (ranksinHand[rank] == 4)
four == TRUE;
if (ranksinHand[rank] == 3)
three == TRUE;
if (ranksinHand[rank] == 2)
pairs++;
}
if (straight && flush){
printf("Straight Flush\n\n");
return(20);
}
else if (four){
printf("Four of a kind\n\n");
return (10);
}
else if (three && pairs == 1){
printf("Full House\n\n");
return (8);
}
else if (flush){
printf("Flush\n\n");
return (5);
}
else if (straight){
printf("Straight\n\n");
return (4);
}
else if (three){
printf("Three of a Kind\n\n");
return (3);
}
else if (pairs == 2){
printf("Two Pairs\n\n");
return (2);
}
else if (pairs == 1){
printf("Pair\n\n");
return (1);
}
else{
printf("High Card\n\n");
return (0);
}
}
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
{
int i, j, carDup;
char suit, rank, ans;
for (i=0; i < 5; i++)
{
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
printf("\nPlease answer (Y/N):");
scanf(" %c", &ans);
if (toupper(ans) == 'Y')
{
finalRank[i] = cardRank[i];
finalSuit[i] = cardSuit[i];
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
continue;
}
else if (toupper(ans) == 'N')
{
carDup = 0;
do{
carDup = 0;
finalRank[i] = (rand() % 13);
finalSuit[i] = (rand() % 4);
for (j=0; j < 5; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
for (j=0; j < i; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1);
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
}
}
}
By convention main() must return an integer. You have to declare it like that:
int main()
{
// Your method
return 0;
}
int mainor
void main
would do the work. Here, int main is shown to be the C standard. Refer to
Return type of main() too.

Connecting Random number in 2d array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have generated random number into a 2d array.What I want now is to connect the same number by moving it inside the game board.The problems is it doesn't move.
I really need help!!! I am new to c programming btw. Thanks in advance.
Here's my code:
void playgame(char box[ROW][COL])
{
int x, y, choice2,num,direction=0;
char input;
do{
printf("Please select a number (1-7) : \n");
scanf("%i",&num);
if(x==0 || x==ROW-1 ||y==0 || y==COL-1)
{
printf("Invalid!\n");
}
else
{
printf("Numer %i is currently selected!\n", num);
}
}while(x==0 || x==ROW-1 ||y==0 || y==COL-1);
printf("[1]Move\n[2]Sign out\n");
printf("Enter choice: ");
scanf("%d", &choice2);
switch(choice2)
{
case 1:
{
printf("Press 'E' to go up\n");
/*codes for moving the character up.....*/
}
{
printf("Press 'D' to go right\n");
/*codes for moving the character down.....*/
}
{
printf("Press 'S' to go left\n");
/*codes for moving the character left.....*/
}
{
printf("Press 'X' to go down\n");
/*codes for moving the character up.....*/
}
{
printf("Press 'R' to remove the existing path\n");
}
fflush(stdin);
scanf("%c", &input);
break;
case 2: printf("Bye!\n");
}
for(x=0; x<9; x++)
for(y=0; y<9; y++)
{
if(input == 'E')
if(box[x][y]==num)
{
box[--x][y]==num;
}
if(input == 'D')
if(box[x][y]==num)
{
box[x][y++]==num;
}
if(input == 'S')
if(box[x][y]== num)
{
box[x][--y]== num;
}
if(input == 'X')
if(box[x][y]==num)
{
box[--x][y]==num;
}
}
}
try this:
#include <stdio.h>
#include <stdlib.h>
#define ROW 9
#define COL 9
void display(char box[ROW][COL]);
int validMove(int r, int c, char box[ROW][COL]);
void playgame(char box[ROW][COL]){
int r, c, num;
int choice, nr, nc;
char input, n;
for(;;){
printf("Please select a number (1-7) : \n");
if(1 == scanf("%i", &num) && 1<= num && num <= 7)
break;
printf("Invalid!\n");
while(getchar() != '\n');
}
printf("Numer %i is currently selected!\n", num);
n = num + '0';
for(r = 1; r < ROW-1; ++r)
for(c = 1; c < COL-1; ++c)
if(box[r][c] == n)
goto find;
find:
for(;;){
printf("[1]Move\n"
"[2]Sign out\n"
"Enter choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Press 'E' to go up\n"
"Press 'D' to go right\n"
"Press 'S' to go left\n"
"Press 'X' to go down\n"
"Press 'R' to remove the existing path\n");
scanf(" %c", &input);
nr = r;
nc = c;
switch(input){
case 'E':
nr = r - 1;
break;
case 'D':
nc = c + 1;
break;
case 'S':
nc = c - 1;
break;
case 'X':
nr = r + 1;
break;
case 'R':
break;
default:
break;
}
if(validMove(nr, nc, box)){
box[nr][nc] = box[r][c];
box[r][c] = ' ';
r = nr;
c = nc;
display(box);
} else if(input != 'R'){
printf("invalid move!\n");
}
break;
case 2: printf("Bye!\n");
exit(0);
}
}
}
int validMove(int r, int c, char box[ROW][COL]){
if(r == 0 || r == ROW-1 || c == 0 || c == COL-1)
return 0;
if(box[r][c] != ' ')
return 0;
return 1;
}
void initBoard(char box[ROW][COL]){
int r, c;
for(r = 0; r < ROW; ++r){
for(c = 0; c < COL; ++c){
if(r == 0 || r == ROW-1 || c == 0 || c == COL-1)
box[r][c] = '#';
else
box[r][c] = ' ';
}
}
for(int i = 1; i <= 7; ++i){
int r = rand() % (ROW-1-1) + 1;
int c = rand() % (COL-1-1) + 1;
if(box[r][c] == ' ')
box[r][c] = i + '0';
else
--i;
}
}
void display(char box[ROW][COL]){
for(int r = 0; r < ROW; ++r){
for(int c = 0; c < COL; ++c){
putchar(box[r][c]);
}
putchar('\n');
}
}
int main(void){
char board[ROW][COL];
initBoard(board);
display(board);
playgame(board);
return 0;
}

Frequency analysis? Caesar cipher C

I have written this code so far, and now i am required to use the frequency analysis to crack the code which I am not not clear of.
From what I understand, I must first count the frequency of letters in a string, then I would say compare it with the most frequent letters in German language, and later sort it with bubble sort. Is this correct?
I would really appreciate it if anyone could give me Ideas or hints on where to start. Thank you in advance.
EDITED: Hi Guys, i just edited my code and the frequency analysis seems to be working fine right now. It would help me if you guys can give comments or critics on my code. Thanks!
BTW its German language, i changed it.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
struct Data
{
char letter;
int num;
};
typedef struct Data DATA;
void encode(char message[], int shift)
{
int i;
FILE *pout;
pout = fopen("Output_encode.txt", "w");
if (pout == NULL)
{
printf("File could not be opened for writing!\n");
exit(1);
}
for(i=0;i<strlen(message);i++)
{
if (!isalpha(message[i]))
continue;
// checking for upper case
if(isupper(message[i]))
message[i]=((message[i]-'A') + shift) % 26 + 'A';
else
//checking for lower case
if(islower(message[i]))
message[i]=((message[i]-'a') + shift) % 26 + 'a';
}
printf("\n\tEncoded text: %s\n", message);
fprintf(pout, "%s\n", message);
if (fclose(pout) != 0)
printf("Error in closing file!\n");
}
void decode(char message[], int shift)
{
int i;
FILE *pout;
pout = fopen("Output_decode.txt", "w");
if (pout == NULL)
{
printf("File could not be opened for writing!\n");
exit(1);
}
for(i=0;i<strlen(message);i++)
{
if (!isalpha(message[i]))
continue;
// checking for upper case
if(isupper(message[i]))
message[i]=((message[i]-'A') + (26-shift)) % 26 + 'A';
else
//checking for lower case
if(islower(message[i]))
message[i]=((message[i]-'a') + (26-shift)) % 26 + 'a';
}
printf("\n\tDecoded text: %s\n", message);
fprintf(pout, "%s\n", message);
if (fclose(pout) != 0)
printf("Error in closing file!\n");
}
void textfile_decode()
{
FILE *pin, *pout;
char filename_in[MAX], filename_out[MAX];
char text[MAX];
char text3[MAX]={0};
char table[26] = {'e','n','i','r','s','t','a','d','h','u','l','c','g','o','m','b','f','w','k','z','p','v','j','y','x','q'}; //Frequency letters in German dictionary
DATA temptext, text2[26];
int temp, position;
int i, m, max, trial, l=0, n=0, k=0;
printf("Enter name of input file: ");
scanf("%s", filename_in);
pin = fopen(filename_in, "r");
if (pin == NULL)
{
printf("File could not be opened for reading!");
}
printf("Enter name of output file: ");
scanf("%s", filename_out);
pout = fopen(filename_out, "w");
if (pout == NULL)
{
printf("File could not be opened for writing!");
}
printf("\nOriginal Code:\n");
while(!feof(pin))
{
fgets(text, MAX, pin); //Read from textfile
fputs(text, stdout); //Show original code on console
}
printf("\n");
if (pin == NULL)
{
printf("File could not be opened for reading!");
}
fclose(pin);
pin = fopen(filename_in, "r");
for (i = 0; i <= 25; i++)
{
text2[i].letter = 'a' + i; //Array elements A-Z
text2[i].num = 0; //Number of letters (Frequency)
}
while(!feof(pin))
{
i = 0;
fgets(text, MAX, pin); //Read from textfile per line
while(text[i] != '\0')
{
if(1 == isupper(text[i])) // Replace capital letters with small
{
text[i] += 32;
}
switch(text[i]) //Counting letters (letter frequency)
{
case 'a':
text2[0].num += 1;
break;
case 'b':
text2[1].num += 1;
break;
case 'c':
text2[2].num += 1;
break;
case 'd':
text2[3].num += 1;
break;
case 'e':
text2[4].num += 1;
break;
case 'f':
text2[5].num += 1;
break;
case 'g':
text2[6].num += 1;
break;
case 'h':
text2[7].num += 1;
break;
case 'i':
text2[8].num += 1;
break;
case 'j':
text2[9].num += 1;
break;
case 'k':
text2[10].num += 1;
break;
case 'l':
text2[11].num += 1;
break;
case 'm':
text2[12].num += 1;
break;
case 'n':
text2[13] .num+= 1;
break;
case 'o':
text2[14].num += 1;
break;
case 'p':
text2[15].num += 1;
break;
case 'q':
text2[16].num += 1;
break;
case 'r':
text2[17].num += 1;
break;
case 's':
text2[18].num += 1;
break;
case 't':
text2[19].num += 1;
break;
case 'u':
text2[20].num += 1;
break;
case 'v':
text2[21].num += 1;
break;
case 'w':
text2[22].num += 1;
break;
case 'x':
text2[23].num += 1;
break;
case 'y':
text2[24].num += 1;
break;
case 'z':
text2[25].num += 1;
break;
default: break;
}
i++;
}
}
for(i = 0; i <= 26; i++) // Sorting array text2 according to letter frequency
{
temp = text2[i].num;
for(m = i+1; m <= 27; m++)
{
if(text2[m].num > temp)
{
max = m;
temp = text2[m].num;
}
}
temptext = text2[max];
text2[max] = text2[i];
text2[i] = temptext;
}
fclose(pin);
fclose(pout);
pin = fopen(filename_in, "r");
pout = fopen(filename_out, "w");
do
{
k += 1;
} while (text2[k].num == text2[k+1].num); //Check--> How many letters have the same frequency
trial = 2;
while(!feof(pin))
{
fgets(text, MAX, pin);
do
{
position = table[l] - text2[n].letter; // determine letter position
i = 0;
do
{
if(0 !=isalpha(text[i]))
{
if(0 != isupper(text[i])) // Checking for uppercase
{
text3[i] = text[i];
text3[i] = text3[i] + position;
if(text3[i] > 90) // If exceeds Alphabets, start again from 'A'
{
text3[i] = text3[i] - 26;
}
else if (text3[i] < 65)
{
text3[i] += 26;
}
}
else if (0 != islower(text[i])) // checking for lowercase
{
text3[i] = text[i];
text3[i] = text3[i] + position;
if(text3[i] > 122) // If exceeds Alphabets, start again from 'a'
{
text3[i] = text3[i] - 26;
}
else if(text3[i] < 97)
{
text3[i] += 26;
}
}
}
else
{
text3[i] = text[i]; // All other non letters are simply replaced
}
i++;
}while(text[i] != '\0' );
if (trial== 2)
{
printf("\n");
fputs(text3, stdout);
printf("\nCode decrypted? (0)NO (1)YES : ");
scanf("%d", &trial);
printf("\n");
}
if (trial == 0 && n != k) // Code not decrypted, letters have different frequency
{
n++;
trial = 2;
}
if (trial == 0 && n == k) // Code not decrypted, letters have same frequency
{
l++;
n = 0;
trial = 2;
}
if (trial == 3) // First line of code is decrypted, following lines will decrypted using same shift position
{
trial = 1;
}
}while(trial != 1);
fputs(text3, stdout); //Show on console window
fputs(text3, pout);
memset(text3,'\0',100); // Reset text3 array
memset(text,'\0',100); // Reset text array
trial = 3; // First line of code decrypted, shift position is saved
}
fclose(pin);
fclose(pout);
}
int main()
{
int shift, choice1, choice2;
char message[MAX];
do{
printf("Selection: \n");
printf("(1) Encode/Decode\n");
printf("(2) Decode Textfile\n");
printf("(3) End Programme\n");
printf("User input: ");
scanf("%d", &choice1);
fflush(stdin);
switch(choice1){
case 1:
printf("\nEnter message to be encrypted: ");
gets(message);
printf("Enter shift amount (1-25): ");
scanf("%d", &shift);
printf("\nSelection: \n");
printf("(1) Encode\n");
printf("(2) Decode\n");
printf("User input: ");
scanf("%d", &choice2);
switch(choice2)
{
case 1:
encode(message, shift);
break;
case 2:
decode(message, shift);
break;
}
break;
case 2:
textfile_decode();
break;
}
printf("\n\n");
}while(choice1!=3);
printf("\n");
return 0;
}
A Caesar ciphre changes characters by shifting them n places.
There are two very simple approaches to solving a shift ciphre:
Print all 25 possible solutions. Manually select the one that contains readable text.
Get the frequency of the characters (not the words). Then perform the shift that best aligns with a frequency table of the language the message was written in (English in your case?).
To break the code you can use 3 different approaches:
The first one is what you cited: count the frequency of words in a text ( I would rather use a Map for that, using the string as key and rising the number of hits as value.), and guessing the letters by comparing it to the frequency of words used in normal texts.
The second solution would be to do same with letters and guessing the meaning by comparing your frequency with the frequency of letters in a normal text.
The third solution would be to take single words of the text and trying all possible shiftings of the letters until you get words that mean something.
Here you can find some good sources!

Resources