How to code Caesar Cipher encryption using file in C - c

For Caesar cipher encryption, I have this code. This program uses text written by the user. But I want this to be read from a text file and run.
#include<stdio.h>
#include <conio.h>
#include<string.h>
void main()
{
int key,i;
char [30];
clrscr();
printf("\n enter plain text : ");
gets(data);
printf("\ enter key value : ");
scanf("%d",&key);
{
for (i=o;i<strlen(data);i++) {
if (data[i]==' ') {}
else
{
if (data[i]>='x')
{
data[i]=data[i]-26;
}
data[i]=data[i]+key;
}
}
}
printf("your cipher text is : %s",data);
getch();
}

Did you just copy and paste this code from somewhere?
As everyone else has already pointed out, there are some pretty big problems with your code, so I'll try and touch on the ones they haven't mentioned throughout. To start though, you should declare main as an int. The return value tells you if the program exited correctly, it's not just convention.
Here is your original code, formatted. I removed conio.h because it's been deprecated for years and moreover you don't need it here. All it was doing was clearing the screen for you, which you can do with System("CLS");, although here is a great article that's been shared many times here on SO that explains why you should refrain from using it.
#include<stdio.h>
#include<string.h>
int main()
{
int key,i;
// original: char [30];
// I'm guess you copied and pasted wrong?
char plainText[30];
printf("\n enter plain text : ");
gets(data);
printf("\nenter key value : ");
scanf("%d",&key);
// You had brackets here, essentially creating an unnecessary
// block of code.
for(i=o;i<strlen(data);i++)
{
// Where did the "data" variable come from? You haven't declared it
// and you're trying to get its length in this for loop
if (data[i]==' ')
{
// ?
}
else
{
if (data[i]>='x')
{
// Instead of this approach I would go with a modulus operation
// If you're not familiar with modular arithmetic I really recommend you look
// it up. It's absolutely essential in cryptography. It's central to both
// symmetric and asymmetric key cryptography.
data[i]=data[i]-26;
}
// This is the heart of the Caesar cipher right here. This is where you're actually
// shifting the characters, so it's a literal Caesar cipher
data[i]=data[i]+key;
}
}
// Again, you haven't declared "data" so you can't call it. I'm guessing you didn't
// try to compile this program because it is teeming with errors GCC, Clang, and VC++
// would have caught immediately
printf("your cipher text is : %s",data);
getch();
// Remember to make your "main" function return an <code>int</code>. This value is
// very important, especially when your program gets called by another program because
// it's how your program communicates that it ran successfully, or something went
// wrong. In that case you could set a specific error code to know exactly
// what went wrong and were
// Example:
int x = 1;
if (x == 1)
exit(4);
// This program would now exit with a status of 4, which you would then know was due
// to this function. This was a contrived example, but hopefully you get the gist
return 0;
}

Related

How to fix: user inputted string not working correctly as a function

I have a successfully written encryption code that asks the user if they want a left shift or right shift and how much they want to shift by.The goal is to make the program work through functions. I was able to get the first part of the code into a function (school programming exercise), but I am stuck on getting the user input. The function is getValidMessage(); I know I've called it correctly in the main code. I think the issue might be with null terminating the string, but I can't figure out what's wrong.
I have a line of code that should null-terminate it, and I think I made enough changes to the original code that it should work. However, I'm not sure that I implemented the code correctly in the function.
// get message to encrypt
//This is called in the main function
char originalMessage[100];
getValidMessage(&originalMessage, sizeof(originalMessage));
int originalMessageLength = strnlen(originalMessage,
sizeof(originalMessage));
//This is the function
/*
* Gets valid message from user
*/
void getValidMessage(char* message, int messageSize)
{
char originalMessage[100];
bool validMessage = false;
printf("\n");
printf("Enter message to be encrypted (upper case alphabetic
characters only): ");
fgets(originalMessage, messageSize, stdin);
int originalMessageLength = strnlen(originalMessage,
messageSize) - 1;
while (!validMessage)
{
// invalid if non-upper case alpha characters in
// message (don't include newline at end))
validMessage = true;
for (int i = 0; i < originalMessageLength; i++)
{
if (!isupper(originalMessage[i]))
{
printf("\n");
printf("Message must contain only upper "
"case alphabetic characters!\n");
printf("Enter message to be encrypted "
"(upper case alphabetic characters only):");
fgets(originalMessage, messageSize, stdin);
originalMessageLength =
strnlen(originalMessage, messageSize) - 1;
// reset flag and exit for loop
validMessage = false;
break;
}
}
}
originalMessage[originalMessageLength] = '\0';
return originalMessage;
}
I am using a running test code that uses MESSAGE. The entirety of the code should encrypt and decrypt the code to show OGUUCIG and then MESSAGE again. Currently, it just shows a bunch of weird characters.
Note: This is NOT the entirety of the code. It doesn't show the encryption or decryption code. I know that works fine, but I can't get it to work smoothly with a separate function instead of in the main body of the code.

Read integer untill user reaches negative integer or numbers of integer reaches upto 15

i wrote following program but it is not right. would you please assist me where i went wrong?
#include<stdio.h>
void main()
{
int count=0,a;
do
{
scanf("%d",&a);
if(a>0 )
{
for(count=0;count<15;count++);
else;
}
while(int>=0);
}
So would you tell me the correct code?
Please use building blocks of correct syntax:
main:
#include <stdio.h>
int main(void)
{
/* other code */
return 0;
}
do-while:
do
{
/* other code */
} while(count>=0);
if:
if(a>0 )
{
/* code if true */
} else
{
/* code if false */
}
for:
for(a=0;a<15;a++)
{
/* repeated code */
}
For getting input right, please read:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ
When the syntax is right and the input is done correctly, then we can discuss the behaviour of your code; which I think is what you are actually asking about. Though what you are describing might already be solved/achieved once you spend some work on how to get input properly, based on the links above.

Assignment to write a program that gives the user a choice between two options - C

I have an assignment due and I am drawing a blank on what exactly to do... I'm sure it is simple but I havent quite gotten the hang of things yet. The assignment is -
Write a program that gives the user 2 menu options: either call a function that will print a greeting and your name 4 times or call a function that will count down from 10 to 0 and then print "Blastoff!". Both functions should use for loops to print the appropriate output.
I have the prompt and the functions done so far... but I am unsure of how to display one or the other depending on the choice the user makes. Thank you for your help.
#include <stdio.h>
int main (void){
// declare counter variable
int i;
// prompt the user to make a choice
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n");
printf("\n");
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
You should read the input from user's keyboard:
int c;
c = getchar();
if (c == '1')
{
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
if (c == '2')
{
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
}
printf("Blastoff!");
you should use Switch case.
switch(choice) {
case 1: //first for loop
break;
case 2: //second for loop
break;
}
Looks like you are missing a couple of points here. Firstly, you have not yet written any functions. Try looking here to gain some insight on that front.
Secondly, to make a choice based on user input you need to actually get that input somehow. You'll probably want to use scanf.
Lastly, once you have the user's input (say, in a variable declared as int input;) you can use if to control the flow of your program based on that variable like this:
if(input == 1){
greet();
}
else {
countDown();
}
Cheers! If you have any further questions feel free to comment below.
First of all you haven't actually declared you functions. Functions in C should be declared like the main function is. For more info in this see here.
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
To get the user's input the most common way is by keyboard. scanf accomplishes that in C. Details on scanf here
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
}
Lastly to decide what to do based on the user input you can use either an if then else statement or a switch. I will provide a solution with an if statement and you can figure the one with the switch on your own. Your final code should look like this.
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
if(choice == 1){
greeting();
}else{
countdown();
}
}
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
Bear in mind that this code has a lot of flaws (error checking mainly) but I guess your assigment is not about that.
First of all you need to include libraries with function you will need. You do this by
#include <someLibrary.h>
at the beggining of you document. Libraries mostly have .h extension. Always look for them if you try to do something. You consider them to have best performance and functionality as possible (not always true).
What is next you declare your functions. Function has name, arguments which are going into it, body in which they do something and return value (can be float, int, char etc). If function doesnt return anything, they return void (dont have return at the end). You declare functions before main() with only types of arguments. Whole body is after main (it is better looking).
If you declared function with arguments, you have to provide these arguments to function in () brackets. Even if no arguments are needed, you use them like getch() in example below. Note that function become what it return. If you declared some new variables in function they will be visible only in function. On the other hand function will not see any variable from other function (main too). If you want so, declare global variables (not recommended).
#include <stdio.h>
#include <conio.h> //libraries
void function1(int);
float function2(float); //declaration of functions
int main()
{
char decision;
printf("press 'a' to run function1, press 'b' to run function2\n");
decision=getch(); //first see getch()? look in google for functionality and library !
int someInt=10;
float someFloat=11;
if(decision== 'a')
{
function1(someInt);
}
else if(decision == 'b')
{
printf("%f", funcion2(someFloat)); //example that function become what they return
}
else
{
printf("No decision has been made");
}
getch(); //program will wait for any key press
return 0;
}
void function1(int param1)
{
//print your stuff // this function return void, so doesnt have return; statement
}
float function2(float param1)
{
return 2*param1; //this function have to return some float
}

function prototype in c, compile error

So am trying to learn c by-myself (basically not having any previous experience in any programming language) and now I have some issues with prototyping some of my functions to use in header files.
For the sake of learning I only use the < stdio.h > lib and only use the printf and scanf functions and for now it only prints to console.
I was able to code a working prototype function for my menu that only uses the printf function but the scanf gives me more issues and it just refuses to compile and am having trouble to see where my thinking error is.
my main program:
#include "menu.h"
#include "circlefunctions.h"
#include "input.h"
int main(void){
float diameter;
double straal;
double oppervlakte;
double omtrek;
while(1){
menu();
user_input();
system("cls");
switch(user_input())
{
case 1:
printf(" ----------------------------------------\n");
printf(" Typ de diameter van de cirkel: ");
scanf("%g", &diameter);
printf(" ----------------------------------------\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
omtrek = 2 * PI * straal;
printf(" De straal = %f \n\n", straal );
printf(" De oppervlakte = %f \n\n" , oppervlakte);
printf(" De omtrek = %f \n" , omtrek);
printf(" ----------------------------------------\n");
break;
case 2:
return(0);
case 3:
return(0);
case 9:
return(0);
case 0:
return(0);
}
}
return 0;
}
and the stubborn header:
#include <stdio.h>
void user_input();
void user_input(){
scanf("%d", &user_input);
}
The error that I get while trying to compile is in input.h
the part with; scanf("%d", &user_input);
errorcode: format '%d' expects argument type of 'int ', but argument 2 has type 'void () ()'.
And I also got an error on the switch in the main program that the switch quantity is not an integer. I suspect that this error is related but am not sure. I still have to debug that part but if anyone is willing to point me to the right documentation i would much appreciate it.
And a second question that I have is also related to headers: I have < stdio.h > already included in "menu.h". Would I need to include it again in "input.h"?
(if i understand correctly how the preprocessor works i should not have to include it but I can't find anywhere where this is explained in simple terms unfortunately.)
Edit:
Thank you all for providing valuable information.
#zenith Thank you for your example. I hope you don't mind me asking some more.
I have replaced my code with yours in the "input.h" and it will compile and run now. However the behavior has changed. For some unclear reason i now have to input the choice twice before the program accepts my input. So the 1st input gets ignored after an enter and it will only accept the 2nd input.
Could you perhaps point me in the direction what causes this bug? or perhaps point me to some documentation where this is explained? I don't want to take up to much of you valuable time of-course.
Edit 2
Thanks for the reply and info. I got the bug out and it is working as intended(that was silly of me not to see that).
And to the rest who replied: Ill take your information of-course and also learn from that. Thank you all!
user_input() doesn't return anything, since it's declared void.
But you're trying to use the non-existing return value: switch(user_input()).
This causes undefined behavior.
Additionally, this:
scanf("%d", &user_input);
tries to read an int from stdin and store it in the memory address of the user_input function. Not a good idea. Again, undefined behavior.
What you probably want the function to look like:
int user_input(){
int number; // store user input to this variable
scanf("%d", &number);
return number; // return the user input so that it can be used outside the function
}
If you have header files declared in a previous header file. You will not need to include it again in the subsequent included header files. I tend to not include header files in my local *.h files just for that reason. It avoids circular includes if you declare your includes in the .c files as much as possible.
Your scanf function has as its second argument a function of type void(), void(). Meaning it takes no arguments and returns nothing or "void". I think you want your user_input to be a variable of type 'double' that is filled somewhere, maybe via some user input from the console using a call to 'gets' from stdin.
HTH

Console application crashes for unknown reason

I have my piece of code which is shown below
#include<cstdlib>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int main()
{
int a;
printf("Please select a choice \n1.Enter New Artist\n2.List All Artist information\n3. Show sorted List of Artists\n4.Add Album to existing Artist\n5.Remove Album from existing Artist\n6.Update Artist info\n7.Search for Artist");
scanf("%d,&a");
if(a==1)
{
printf("no");
}
system("PAUSE");
return EXIT_SUCCESS;
}
On running the code, it displays the menu and if i input 1, it takes a few seconds before it crashes and displays the info
document1.exe has stopped working
How can I debug this problem. I am using dev c++ 4.9.9.2
Your scanf statement is wrong. You are not passing argument (pointer) to it.
Change
scanf("%d,&a");
to
scanf("%d",&a);
For a C solution - I am not certain
aside from previously mentioned
error in scanf formatting (which your compiler should have warned about),
which would have put the result.. well, god knows where on stackā€¦
I'm not certain, but I suspect the compiled code would take the next location in ram as an address, and write there.
Borked stack == really, really, really hard to debug errors.
Since you are using a c++ compiler, if you can use c++, you may wish to consider evaluation of using some of the STL here.
I assume you will be terminating input with a CR
int main (int argv, char** argv]
{
int a;
std::string inputString;
std::cout <<"Please select a choice \n""1.Enter New Artist\n2.List All Artist information\n3. Show sorted List of Artists\n4.Add Album to existing Artist\n5.Remove Album from existing Artist\n6.Update Artist info\n7.Search for Artist";
std::getline(std::cin,inputString);
std::stringstream inputStream(inputString);
inputStream >> a; // could also have been parsed with std::stol, or strtol. - my preference due to error checking - what if your user entered 'byte me'?
if (a==1)
{
printf("no");
}
system("PAUSE");
return EXIT_SUCCESS;
}

Resources