Simple Caesar Cipher Program in C - c

Hey guys I'm starting to learn C, and I was asked to code a program specifically, a caesar cipher (so, the idea is to replace any letter in the message by a letter three positions down the alphabet.)
My implementation should read a line of text and then either performs encryption or decryption, depending on the first character read. If the first character is $, then I'm supposed to encrypt the rest of the line, and precede the output by the character ?. If the first character is ?, then I'm supposed to decrypt the rest of the line, and precede my output by the character $.
So for example: ?Wr eh, ru qrw wr eh
the output should be: $To be, or not to be
and vice versa.
So this is my code so far:
#include <stdio.h>
int main(void){
char code[100], ch;
int i;
scanf("%s", &code);
if(code[0] == '$'){
for(i = 0; code[i] != '\0'; ++i){
ch = code[i];
if(ch >= 'a' && ch <= 'z'){
ch = ch + 3;
if(ch > 'z'){
ch = ch - 'z' + 'a' - 1;
}
code[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch + 3;
if(ch > 'Z'){
ch = ch - 'Z' + 'A' - 1;
}
code[i] = ch;
}
}
printf("?%s\n", code);
return 0;
}
}
But the problem is, it returns the first character and stops whenever there are space.
Like for example I enter: $To be it outputs to: ?$To
Can someone please help me figure out what I'm doing wrong?

Here's a sample using getchar() to get you started:
#include <stdio.h>
int main() {
int ch; // Either EOF or one of the chars in 0-255
while ((ch = getchar()) != EOF) {
if ('A' <= ch && ch <= 'Z') {
int offset = ch - 'A';
printf("%c", 'a' + offset);
} else {
printf("%c", ch);
}
}
}
Now, this code isn't perfect in a lot of ways, but it does demonstrate how to use getchar(). Every time getchar() is called, it fetches the next char from standard input and returns it as an int. That's because when the input is over, it returns the special value EOF, which is outside the range of char.
The while loop here is a common idiom. When execution reaches the loop, it first has to call getchar(), whose result is stored into ch. Then it checks whether ch is EOF. If not, then the loop processes the character that was read. Otherwise, it exits and the program ends.
The body of the loop prints every character it sees, while converting the uppercase letters to lowercase.

Related

How do I store a value in a file to an array?

I have a txt file that looks like the following:
1:0
2:0
3:1
4:0
...
99:1
100:1
I would like to store the 1s and 0s inside an array (slot[]), (regardless of what's on the left side of the ':'s), but I can't figure out how. Here's a snippet of my code for that:
while((ch=fgetc(fptr)) != EOF)
{
if(ch == ':')
{
slot[j] = fgetc(fptr); //saves the character right after ":"into slot[j]?
j++;
}
}
I know it's more complicated than this because it doesn't work. I've searched for a long time but can't find it, maybe because I didn't search for the correct terms.
How can I fix this?
Thanks in advance.
It seems pretty straight forward with some minor changes, since your specs state that there is always 1 digit on the right and is always 0 or 1, something like this should do it:
if (fptr != NULL)
{
int ch;
int j = 0;
while ((ch = fgetc(fptr)) != EOF)
{
if (ch == ':')
{
if ((ch = fgetc(fptr)) != EOF) // get digit after :
{
slot[j++] = ch - '0'; // for int array *
//slot[j++] = ch; // for char array
}
else
{
break;
}
}
}
}
Or, for a more robust method using fgets:
if (fptr != NULL)
{
char temp[100]; // must be large enough to hold the line
char *ch;
int j = 0;
while (fgets(temp, sizeof temp, fptr)) // read whole line
{
ch = strchr(temp, ':'); // find :
if (ch != NULL && (ch[1] == '1' || ch[1] == '0'))
{
// add next digit to slot[] if it's 1 or 0
slot[j++] = ch[1] - '0'; // or remove - '0' for char slot[]
}
}
}
Requires string.h header for strchr.
* Check this post if you want to know more about character to digit conversion:
Why is there a need to add a '0' to indexes in order to access array values?
The reason it doesn't do what you expect is because you are reading characters and expecting them to be numbers. A character in C has an integer value. The mapping is called ASCII (have an internet search for "ASCII table"). The uppercase alphabet starts at 65, the lower case alphabet starts at 97, and the numeric digits start at 48. So, if '0' is 48 and '1' is 49 you can change '0' and '1' to 0 and 1 respectively by subtracting 48 from each:
slot[j] = fgetc(fptr) - 48;
And that works but later you will forget what 48 means and have to look at an ASCII table again so you should use characters:
slot[j] = fgetc(fptr) - '0';
Which does the same exact thing but makes it obvious why you are subtracting a value.
You can use the same trick to convert upper case to lower case:
if (ch >= 'A' && ch <= 'Z') ch += 32;
Or lower case to upper case:
if (ch >= 'a' && ch <= 'z') ch -= 32;
But of course, there are library functions called tolower() and toupper() which are much more expressive which is why nobody does it that way.

C program to capitalize a word inside quotation marks

I need to build a function that gets an input and capitalizes only the first letter, doesn't print numbers, capitalizes after a . for a new sentence, and capitalizes all words between a double quotation marks ".
This is what I got until now:
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX] = { 0 };
int i;
//input string
printf("Enter a string: ");
scanf("%[^\n]s", str); //read string with spaces
//capitalize first character of words
for (i = 0; str[i] != '\0'; i++)
{
//check first character is lowercase alphabet
if (i == 0)
{
if ((str[i] >= 'a' && str[i] <= 'z'))
str[i] = str[i] - 32; //subtract 32 to make it capital
continue; //continue to the loop
}
if (str[i] == '.')//check dot
{
//if dot is found, check next character
++i;
//check next character is lowercase alphabet
if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] = str[i] - 32; //subtract 32 to make it capital
continue; //continue to the loop
}
}
else
{
//all other uppercase characters should be in lowercase
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = str[i] + 32; //subtract 32 to make it small/lowercase
}
}
printf("Capitalize string is: %s\n", str);
return 0;
}
I cant find a way to remove all numbers from input and convert all lowercase to uppercase inside a " plus code for not printing numbers if user input them.
if I input
I am young. You are young. All of us are young.
"I think we need some help. Please" HELP. NO, NO NO,
I DO NOT
NEED HELP
WHATSOEVER.
"Today’s date is
15/2/2021"...
I am 18 years old, are you 20 years old? Maybe 30 years?
output:
I am young. You are young. All of us are young.
"I THINK WE NEED SOME HELP. PLEASE" help. No, no no,
i do not
need help
whatsoever.
"TODAY’S DATE IS
//"...
I am years old, are you years old? maybe years?
The C standard library provides a set of functions, in ctype.h, that will help you
Of particular interest, would be:
isdigit() - returns true if digit
isalpha() - returns true if alphabet character
isalnum() - returns true if alpha/numeric character
islower() - returns true if lower case character
isupper() - returns true if upper case character
tolower() - converts character to lower case
toupper() - converts character to upper case
So, for example, you could replace the test/modify with:
if ( islower( str[i] ) )
{
str[i] = toupper( str[i] );
}
Pedantically, islower() and toupper() return an unsigned int but that's a separate matter...
You can remove letters from a string if you keep two indices, one for reading and one for writing. The following loop will remove all digits from a string:
int j = 0; // writing index, j <= i
int i; // reading index
for (i = 0; str[i]; i++) {
int c = (unsigned char) str[i];
if (!isdigit(c)) str[j++] = c;
}
str[j] = '\0';
(I've used to character classification functions from <ctype.h> mentioned in Andrew' answer.)
This is safe, because j will always be smaller or equal to i. Don't forget to mark the end of the filtered string with the nullterminator, '\0'. You can combine this filtering with your already existing code for replacing characters.
In your code, you capitalize letters only if they are directly behind a full stop. That's usually not the case, there's a space between full stop and the next word. It's better to establish a context:
shift: capitalize the next letter (beginning or after full stop.)
lock: capitalize all letters (inside quotation marks.)
When you read a letter, decide whether to capitalize it or not depending of these two states.
Putting the filtering and the "shift context§ together:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char str[] = "one. two. THREE. 4, 5, 6. \"seven\", eight!";
int shift = 1; // Capitalize next letter
int lock = 0; // Capitalize all letters
int j = 0; // writing index, j <= i
int i; // reading index
for (i = 0; str[i]; i++) {
int c = (unsigned char) str[i];
if (isdigit(c)) continue;
if (isalpha(c)) {
if (shift || lock) {
str[j++] = toupper(c);
shift = 0;
} else {
str[j++] = tolower(c);
}
} else {
if (c == '"') lock = !lock;
if (c == '.') shift = 1;
str[j++] = c;
}
}
str[j] = '\0';
puts(str);
printf("(length: %d)\n", j);
return 0;
}
In order to remove some characters, you should use 2 index variables: one for reading and one for writing back to the same array.
If you are allowed to use <ctype.h>, it is a much more portable and efficient way to test character types.
Also do not use scanf() with protection against buffer overflow. It is as bad as using gets(). Given the difficulty in specifying the maximum number of bytes to store into str, you should use fgets() instead of scanf().
Here is a modified version:
#include <ctype.h>
#include <stdio.h>
#define MAX 100
int main() {
char str[MAX];
int i, j;
unsigned char last, inquote;
//input string
printf("Enter a string: ");
if (!fgets(str, sizeof str, stdin)) { //read string with spaces
// empty file
return 1;
}
last = '.'; // force conversion of first character
inquote = 0;
//capitalize first character of words
for (i = j = 0; str[i] != '\0'; i++) {
unsigned char c = str[i];
//discard digits
if (isdigit(c)) {
continue;
}
//handle double quotes:
if (c == '"') {
inquote ^= 1;
}
//upper case letters after . and inside double quotes
if (last == '.' || inquote) {
str[j++] = toupper(c);
} else {
str[j++] = tolower(c);
}
if (!isspace(c) && c != '"') {
// ignore spaces and quotes for the dot rule
last = c;
}
}
str[j] = '\0'; // set the null terminator in case characters were removed
printf("Capitalized string is: %s", str);
return 0;
}

Only first char of user input used in array

I am writing some code for a nanokernel, which means I can't use the standard library, although I have implemented functions for printing strings and getting chars from the keyboard.
Right now I have the program set up to take chars from the keyboard and put them into an array. The string is then printed out. I expect the string printed out to look exactly like what was inputted by the user.
The issue is that it seems that the only char being put into the string is the first char inputted on the keyboard.
here is the relevant code for putting the chars into an array:
void stringin(char str[]) { // takes a string, puts it in str
int i = 0;
for (i = 0; str[i] != '\n' && str[i] != '\033';) {
str[i] = getch();
if (str[i] != '\n' && str[i] != '\033') {
i++;
}
calctime(1000000); // waits for a bit so that we don't flood the array
}
if (str[i] == '\n') newline(1);
str[i++] = '\0';
}
I have used both a printing function and a strcmp() implementation to test the contents of the string, so nothing seems to be going wrong with printing the string.
Based on the comments, str is passed to stringin with the buffer uninitialized.
Since the following loop terminates based on the value of str[i] before str[i] is actually initialized, the results are undefined.
for (i = 0; str[i] != '\n' && str[i] != '\033';) {
str[i] = getch();
....

Encryption with swapping letters in C

I need to write a program that reads from the input a sentence terminated by a new line. The program should write an encryption of the sentence in a way that the letter 'a' is swapped with 'z', 'b' with 'y' and so on. I am not supposed to use arrays, that is why I can't find a solution for this problem.
This is my code:
#include<stdio.h>
int main() {
char alphabet, temp;
while( scanf("%c", &alphabet) != '\n') {
for(char i ='a', j='z'; i <= 'z', j>='a'; i++, j--) {
if(alphabet == i) {
temp = j;
}
}
printf("%c", temp);
}
return 0;
}
When I input: abc as an output I get zyxxxxxxxxxxxxxxxxxxxxxxxxx(an infinite number of x).
So to sum up:
Input:abc. Output: zyxxxxx(infinite number of x).
You messed up the return value of scanf:
while( scanf("%c", &alphabet) != '\n'){
You want to stop the loop when the entered character (in alphabet) is a line break.
But you test the return value of scanf which will never be '\n' as it returns the number of converted fields.
You could try like this:
while( scanf("%c", &alphabet) == 1 && alphabet != '\n'){
Compile your code with warnings enabled (e.g. Wall flag)! This:
for(char i ='a', j='z'; i <= 'z', j>='a'; i++, j--)
should give:
warning: left-hand operand of comma expression has no effect [-Wunused-value]
You need to use the logical AND operator && and not a comma between the two comparissons.
Moreover, use getchar() instead, like this:
#include<stdio.h>
int main() {
char temp;
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
for(char i ='a', j='z'; i <= 'z'&& j>='a'; i++, j--){
if(ch == i){
temp = j;
}
}
if(ch <= 'z'&& ch >= 'a') // do not print if 'ch' is a digit for example
printf("%c", temp);
}
return 0;
}
Output:
zyx
If you have to use scanf(), then try reading into alphabet, check the return value of scanf, and compare to newline, like this:
while(scanf("%c", &alphabet) != 0 && alphabet != '\n')

Exceptions in c programming language

I'm learning c language and I hit a wall, if you would like to help me I appreciate (here is the ex: "Write a program that reads characters from the standard input to end-of-file. For each character, have the program report whether it is a letter. If it is a letter, also report its numerical location in the alphabet and -1 otherwise." btw is not homework).The problem is with the \n i don't know how to make it an exception. I'm new around here please let me know if I omitted something. Thank you for your help.
int main(void)
{
char ch;
int order;
printf("Enter letters and it will tell you the location in the alphabet.\n");
while ((ch = getchar()) != EOF)
{
printf("%c", ch);
if (ch >= 'A' && ch <= 'Z')
{
order = ch - 'A' + 1;
printf(" %d \n", order);
}
if (ch >= 'a' && ch <= 'z')
{
order = ch - 'a' + 1;
printf(" %d \n", order);
}
if (order != (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
{
if (ch == '\n');
else if (order != (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
printf(" -1 \n");
}
}
system("pause");
}
You are talking about an "exception" which can be interpreted in other ways in programming.
I understand that you want that '\n' be "excepted" in the set of nonalphabetical characters, that is, that it doesn't generate the error value -1.
Since you are using console to run the program, a sequence of character is going to be read till ENTER key is pressed, which generates the character \n. So, I'm not pretty sure that the while() condition you used, that compares against EOF, it's a good decision of yours.
I would put there directly the comparisson against '\n'.
while ((ch = getchar()) != '\n')
To inform if ch is a letter or not, we could use string literals. The following use of string assignment would deserve more explanation, but I will omit it. It's valid with string literals:
char *info;
if (order != -1)
info = "is a letter";
else
info = "is not a letter";
You are assuming an encoding where the letters are in contiguous increasing order (as in ASCII).
By assuming that, it's enough to work with uppercase or lowercase letters, since you are only interested in the position that the letter occupy in the alphabet. So, you can choose to work with uppercase, for example, in this way:
if (ch >= 'a' && ch <= 'z')
ch = (ch - 'a' + 'A');
The effect of that line of code is that ch is converted to uppercase, only if ch is a lowercase letter. Another kind of character is not affected.
As a consequence, from now on, you only have uppercase letters, or nonalphabetical characters.
Then it's easy to code the remaining part:
if (ch >= 'A' && ch <= 'Z')
order = ch - 'A' + 1; // It brings no. position of letter in alphabet
else
order = -1; // This is the erroneous case
A printf() at the end of the loop could bring all the information about the character:
printf(" %16s: %4d \n", info, order);
The resulting code is shorter in more clear:
#include <stdio.h>
int main(void) {
char ch;
int order;
char *info;
while ((ch = getchar()) != '\n') {
printf("%c",ch);
if (ch >= 'a' && ch <= 'z') /* Converting all to uppercase */
ch = (ch - 'a' + 'A');
if (ch >= 'A' && ch <= 'Z')
order = ch - 'A' + 1; /* Position of letter in alphabet */
else
order = -1; /* Not in alphabet */
if (order != -1)
info = "is a letter";
else
info = "is not a letter";
printf(" %16s: %4d \n", info, order);
}
}
If you need to end the input by comparing against EOF, then the type of ch has to be changed to int instead of char, so you can be sure that the EOF value (that is an int) is properly held in ch.
Finally, this means that ch needs initialization now, for example to a neutral value in the program, as '\n'.
Finally, just for fun, I add my super-short version:
#include <stdio.h>
int main(void) {
int ch, order;
while ((ch = getchar()) != '\n') {
order = (ch>='a' && ch<='z')? ch-'a'+1:((ch>='A' && ch<='Z')? ch-'A'+1: -1);
printf("%c %8s a letter: %4d \n", ch, (order != -1)? "is":"is not", order);
}
}
The C language does not have exceptions. Exceptions were first introduced into programming in C++. You can do it manually in C using setjmp() and longjmp(), but it really isn't worth it.
The two most popular of doing error handling in C are:
Invalid return value. If you can return -1 or some other invalid value from a function to indicate 'there was an error', do it. This of course doesn't work for all situations. If all possible return values are valid, such as in a function which multiplies two numbers, you cannot use this method. This is what you want to do here - simply return -1.
Set some global error flag, and remember to check it later. Avoid this when possible. This method ends up resulting in code that looks similar to exception code, but has some serious problems. With exceptions, you must explicitly ignore them if you don't want to handle the error (by swallowing the exception). Otherwise, your program will crash and you can figure out what is wrong. With a global error flag, however, you must remember to check for them; and if you don't, your program will do the wrong thing and you will have no idea why.
First of all, you need to define what you mean by "exception"; do you want your program to actually throw an exception when it sees a newline, or do you simply want to handle a newline as a special case? C does not provide structured exception handling (you can kind-of sort-of fake it with with setjmp/longjmp and signal/raise, but it's messy and a pain in the ass).
Secondly, you will want to read up on the following library functions:
isalpha
tolower
as they will make this a lot simpler; your code basically becomes:
if ( isalpha( ch ) )
{
// this is an alphabetic character
int lc = tolower( ch ); // convert to lower case (no-op if ch is already lower case)
order = lc - 'a' + 1;
}
else
{
// this is a non-alphabetic character
order = -1;
}
As for handling the newline, do you want to just not count it at all, or treat it like any other non-alphabetic character? If the former, just skip past it:
// non-alphabetic character
if ( ch == '\n' )
continue; // immediately goes back to beginning of loop
order = -1;
If the latter, then you don't really have to do anything special.
If you really want to raise an honest-to-God exception when you see a newline, you can do something like the following (I honestly do not recommend it, though):
#include <setjmp.h>
...
jmp_buf try;
if ( setjmp( try ) == 0 ) // "try" block
{
while ( (ch = getchar() ) != EOF )
{
...
if ( ch == '\n' )
longjmp( try, 1 ); // "throw"
}
}
else
{
// "catch" block
}
I'm having hard time trying to understand why you even try to handle '\n' specifically.
You might be trying to implement something like this:
int main(void)
{
char ch;
int order;
printf("Enter letters and it will tell you the location in the alphabet.\n");
while ((ch = getchar()) != EOF)
{
printf("%c", ch);
if (ch >= 'A' && ch <= 'Z') {
order = ch - 'A' + 1;
printf(" %d \n", order);
} else if (ch >= 'a' && ch <= 'z') {
order = ch - 'a' + 1;
printf(" %d \n", order);
} else if (ch == '\n') { } else {
printf(" -1 \n");
}
}
system("pause");
}
While this is a good solution, I would recommend rewriting it in a more optimal way:
int main(void)
{
char ch;
printf("Enter letters and it will tell you the location in the alphabet.\n");
while ((ch = getchar()) != EOF)
{
int order;
if (ch != '\n'){
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') {
order = ch & 11111B;
printf("Letter %d\n", order);
} else {
order = -1;
printf("Not letter: %d\n", order);
}
}
}
system("pause");
}
This way the program relies on specific way letters coded in ASCII

Resources