Caesar code in C extra letter for result - c

#include <stdio.h>
void caesar(char bemenet[], char eredmeny[], int n){
int i = 0;
for(i = 0; bemenet[i] != '\0'; i++) {
if(bemenet[i] == 'z') {
eredmeny[i] = 'a';
eredmeny[i] += n-1;
}
else
{
eredmeny[i] += n;
}
}
eredmeny[i] = '\0';
}
int main(){
char tomb1[]="caesarkodolas";
char tomb2[]="";
caesar(tomb1,tomb2,1);
printf("%s \n",tomb2);
return 0;
}
My out for the "eredmeny" (result) this:
"dbftbslpepmb" but tomb2=> ☺dbftbslpepmb it's not OK.. cause I have an extra char |☺|..

Allocate enough memory for the second parameter, and change this line
eredmeny[i] += n;
to this:
eredmeny[i] = bemenet[i] + n;
Note that this is not a bulletproof implementation of Caesar cipher: it would work for n==1, but it will break for larger n.
You need to think of a different way of implementing the "wrap-around": rather than testing for 'z' and replacing it with 'a', compute the new position of a letter modulo 26, and then add a to it:
void caesar(char bemenet[], char eredmeny[], int n){
int i;
for(i = 0; bemenet[i] != '\0'; i++) {
// Compute the position of the replacement letter
int pos = (bemenet[i] - 'a' + n) % 26;
// Place the letter into the output.
eredmeny[i] = 'a' + pos;
}
eredmeny[i] = '\0';
}
demo.

First of all you should have tomb2 big enough to store result.
For example, as mentioned above
char tomb2[255] = {0};
Also you have error here
else
{
eredmeny[i] += n;
}
You have to assign valid ASCII value to eredmeny[i] so change this string to
eredmeny[i] += bemenet[i] + n
Also it usually bad practice to pass a pointer on array without passing its size. Easy to get buffer overflow.

you're not doing the maths right.
if you are using just lower case letters then you need to add n, but then many letters will be "after" z, so you need to start again at a.
you want something more like this:
for(i = 0; bemenet[i] != '\0'; i++) {
int encrypted = bemenet[i] + n;
if (encrypted > 'z') encrypted = encrypted - 'z' + 'a';
eredmeny[i] = (char)encrypted;
}
(and also fix the output array size as described in other answers here).

Related

C - Cycle through all possible lowercase strings

I'm learning C with the CS50 course problem set 2, using the crypt function to brute force guess a password. Currently writing a function that prints all possible strings of a certain length, eg:
aa
ab
...
az
ba
...
zy
zz
I've written a fairly simple recursive function to do so:
#include <cs50.h>
#include <stdio.h>
#include <crypt.h>
#include <string.h>
void stringcycler(int n, int passLength, char *pass)
// Scrolls through all lowercase letter combinations for a string of length passLength
// Expects an integer value of the length of the strng as both n and passLength
// Also expects a char* array of length passLength with all chars set to 'a' (and a null character)
{
if(n != 0)
{
for(pass[passLength - n] = 'a'; pass[passLength - n] < 'z'; pass[passLength - n]++)
{
stringcycler(n-1, passLength, pass);
printf("%s\n", pass);
// return 0;
}
}
}
int main()
{
// Initialise char *c, and scroll through letters
int passLength = 2; // The number of characters you want to brute force guess
char pass[passLength + 1]; // Add 1 for the null character
int i;
for(i = 0; i < passLength; i++) pass[i] = 'a'; // Set every char in pass to 'a'
pass[passLength] = '\0'; // Set null character at the end of string
stringcycler(passLength, passLength, pass);
return 0;
}
It works for the most part, but only goes to yz. Whenever it sees a z it basically skips, so it goes to yz, then never does za to zz. If I add an = to the for loop line:
pass[passLength - n] < 'z';
ie.
pass[passLength - n] <= 'z';
Then it prints '{' characters in the mix. Any help? And another question is, how can I change this to work for all combos of upper and lower case too, is there a neat way of doing it?
You print after you return from you recursion, but you should print when the recursion has reached the end (or beginning, in your case) of the string. In other words, printing should be an alternative branch to recursing:
void stringcycler(int n, int len, char *pass)
{
if (n != 0) {
for (pass[len - n] = 'a'; pass[len - n] <= 'z'; pass[len - n]++) {
stringcycler(n - 1, len, pass);
}
} else {
printf("%s ", pass);
}
}
The if part constructs the strings as it recurses further down. The else part does something with the constructed string. (Of course, you must include 'z' in your loop. Your original code only prints the z in the last place, because it prints after ther recursion returns, which means thet the char buffer is in a condition that wouldn't (re-)enter the loop.)
Below is a generic backtracking algorithm for generating the password. The idea here is to imagine filling the slots for a given char array a. We will be generating the possible candidates for the given position k for the array a. I have taken the candidates as lower case ascii letters a-z and upper case ASCII letters A-Z. If you want to include other ASCII characters, just modify the construct_candidates function accordingly.
Once the array is filled i.e. k becomes PASS_LEN, we know we have generated the password, we can process it however we like, I have just printed the password here.
The value of PASS_LEN macro can be adjusted to generate password of any desired length.
#include <stdio.h>
#include <stdlib.h>
#define PASS_LEN 2
static char* construct_candidates (char a[], int k, int *count)
{
/* Lower case ASCII */
int min1 = 97;
int max1 = 122;
/* Upper case ASCII */
int min2 = 65;
int max2 = 90;
*count = (max1 - min1 + 1) + (max2 - min2 + 1);
char *cand = calloc(*count, sizeof(char));
if (cand == NULL) {
printf("malloc failed\n");
return NULL;
}
int idx = 0;
for (int i = min1; i <= max1; i++) {
cand[idx] = i;
idx++;
}
for (int i = min2; i <= max2; i++) {
cand[idx] = i;
idx++;
}
return cand;
}
static void backtrack(char a[], int k)
{
int i;
if (k == PASS_LEN) {
for (i = 0; i < PASS_LEN; i++) {
printf("%c", a[i]);
}
printf("\n");
return;
}
int cand_count = 0;
char *cand = construct_candidates(a, k, &cand_count);
if (cand == NULL) {
printf("Failed to get candidates\n");
return;
}
for (i = 0; i < cand_count; i++) {
a[k] = cand[i];
backtrack(a, k + 1);
}
free(cand);
}
int main()
{
char a[PASS_LEN] = {'\0'};
backtrack(a, 0);
}

Exception thrown: read access violation

i'm a beginner and my english is not well so sorry first. im trying to sum the numbers in a string (for a14fg5pk145 it returns 14+5+145), and it doesn't work:
"Exception thrown: read access violation.
str was 0x61."
this i my code:
void main()
{
int x, i;
char* pp;
char buffer[SIZE];
printf("Please enter numbers and letters:\n");
gets(buffer);
pp = buffer;
x = SumStr(*pp);
printf("%d", x);
}
int SumStr(char* str)
{
int sum=0, num=0, flag = 0;
while ((*str) != '\0')
{
while (((*str) > '1') && ((*str) < '9'))
{
if (flag == 0)
{
num += (*str);
flag = 1;
}
else if (flag == 1)
num = num * 10 + (*str);
str++;
}
if (flag == 0)
str++;
sum += num;
num = 0;
flag = 0;
}
return sum;
}
First problem with your code which is causing Exception.
x = SumStr(*pp);
it should be
x = SumStr(pp);
Because you should pass address of the string pointer not its first character by attaching asterix.
Second Issue that will not make it work is.
num += (*str);
and
num = num * 10 + (*str);
By (*str) you are actually adding the character ascii value instead of number.
This will solve the problem by changing the ascii value to number.
num += (*str) - '0';
num = num * 10 + (*str) - '0';
This may serve your purpose
#include<stdio.h>
#include<string.h>
int main()
{
int i, sum = 0, store;
char str[] = "a14fg5pk145asdasdad6";
int length = strlen(str);
for(i = 0; i < length; i++) {
store = 0;
while(isdigit(str[i])) {
store = (store * 10) + (str[i] - '0');
i++;
}
sum += store;
}
printf("%d\n", sum);
return 0;
}
output :
170
Pass pp, not *pp, to the function SumStr. *pp has the type char, and the function expects char *. In fact, you do not even need pp at all, just pass the buffer as the parameter.
Also:
Never use gets(). Because it is impossible to tell without knowing the
data in advance how many characters gets() will read, and because
gets() will continue to store characters past the end of the buffer, it
is extremely dangerous to use. It has been used to break computer
security. Use fgets() instead.

How do I allocate memory to my char pointer?

My assignment is to allow the user to enter any input and print the occurrences of letters and words, we also have to print out how many one letter, two, three, etc.. letter words are in the string. I have gotten the letter part of my code to work and have revised my word function several times, but still can't get the word finding function to even begin to work. The compiler says the char pointer word is undeclared when it clearly is. Do I have to allocate memory to it and the array of characters?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void findLetters(char *ptr);
void findWords(char *point);
int main()
{
char textStream[100]; //up to 98 characters and '\n\ and '\0'
printf("enter some text\n");
if (fgets(textStream, sizeof (textStream), stdin)) //input up to 99 characters
{
findLetters(textStream);
findWords(textStream);
}
else
{
printf("fgets failed\n");
}
return 0;
}
void findLetters(char *ptr) //find occurences of all letters
{
int upLetters[26];
int loLetters[26];
int i;
int index;
for (i = 0; i < 26; i++) // set array to all zero
{
upLetters[i] = 0;
loLetters[i] = 0;
}
i = 0;
while (ptr[i] != '\0') // loop until prt[i] is '\0'
{
if (ptr[i] >= 'A' && ptr[i] <= 'Z') //stores occurrences of uppercase letters
{
index = ptr[i] - 'A';// subtract 'A' to get index 0-25
upLetters[index]++;//add one
}
if (ptr[i] >= 'a' && ptr[i] <= 'z') //stores occurrences of lowercase letters
{
index = ptr[i] - 'a';//subtract 'a' to get index 0-25
loLetters[index]++;//add one
}
i++;//next character in ptr
}
printf("Number of Occurrences of Uppercase letters\n\n");
for (i = 0; i < 26; i++)//loop through 0 to 25
{
if (upLetters[i] > 0)
{
printf("%c : \t%d\n", (char)(i + 'A'), upLetters[i]);
// add 'A' to go from an index back to a character
}
}
printf("\n");
printf("Number of Occurrences of Lowercase letters\n\n");
for (i = 0; i < 26; i++)
{
if (loLetters[i] > 0)
{
printf("%c : \t%d\n", (char)(i + 'a'), loLetters[i]);
// add 'a' to go back from an index to a character
}
}
printf("\n");
}
void findWords(char *point)
{
int i = 0;
int k = 0;
int count = 0;
int j = 0;
int space = 0;
int c = 0;
char *word[50];
char word1[50][100];
char* delim = "{ } . , ( ) ";
for (i = 0; i< sizeof(point); i++) //counts # of spaces between words
{
if ((point[i] == ' ') || (point[i] == ',') || (point[i] == '.'))
{
space++;
}
}
char *words = strtok(point, delim);
for(;k <= space; k++)
{
word[k] = malloc((words+1) * sizeof(*words));
}
while (words != NULL)
{
printf("%s\n",words);
strcpy(words, word[j++]);
words = strtok(NULL, delim);
}
free(words);
}
This is because you are trying to multiply the pointer position+1 by the size of pointer. Change line 100 to:
word[k] = malloc(strlen(words)+1);
This will solve your compilation problem, but you still have other problems.
You've got a couple of problems in function findWords:
Here,
for (i = 0; i< sizeof(point); i++)
sizeof(point) is the same as sizeof(char*) as point in a char* in the function fincdWords. This is not what you want. Use
for (i = 0; i < strlen(point); i++)
instead. But this might be slow as strlen will be called in every iteration. So I suggest
int len = strlen(point);
for (i = 0; i < len; i++)
The same problem lies here too:
word[k] = malloc((words+1) * sizeof(*words));
It doesn't makes sense what you are trying with (words+1). I think you want
word[k] = malloc( strlen(words) + 1 ); //+1 for the NUL-terminator
You got the arguments all mixed up:
strcpy(words, word[j++]);
You actually wanted
strcpy(word[j++], words);
which copies the contents of words to word[j++].
Here:
free(words);
words was never allocated memory. Since you free a pointer that has not been returned by malloc/calloc/realloc, the code exhibits Undefined Behavior. So, remove that.
You allocated memory for each element of word. So free it using
for(k = 0; k <= space; k++)
{
free(word[k]);
}
Your calculation of the pointer position+1 is wrong. If you want the compilation problem will go away change line 100 to:
word[k] = malloc( 1 + strlen(words));

Can't get a function call in a function to work properly

I'm writing a program to generate a string of random uppercase letters, then take user input of uppercase letters, along with a character form the user. For any instance of the user input letter in the random string, it replaces that letter with the character entered by the user.
For example, s1 = {BDHFKYL} s2 = {YEIGH} c = '*'
Output = BD*FK*L
The program was working correctly until I added the feature to ask the user to enter what character they would like to replace the letters.
The output is:
Please enter at least 2 capital letters and a maximum of 20.
HDJSHDSHDDS
HDJSHDSHDDS
Enter a character to replace occuring letters.
*
NWLRBBMQB
Would you like to enter another string?
Here's the code:
void fillS1(char x[]);
void fillS2(char x[], char y[], char z);
void strFilter(char a[], char b[], char c);
int main(int argc, const char * argv[])
{
char s1[42];
char s2[22];
char x = 0;
fillS2(s2, s1, x);
return 0;
}
void fillS1(char x[])
{
for (int i = 0; i < 40; i++)
x[i] = 'A' + random() % 26;
x[40] = (char)0;
}
void fillS2(char x[], char y[], char z){
char loopContinue = 0;
do {
int i = 0;
int capitalLetterCheck = 0;
printf("Please enter at least 2 capital letters and a maximum of 20.\n");
while (( x[i] = getchar()) != '\n' ) {
i++;
}
x[i] = '\0';
if (i < 3) {
printf("You need at least two letters\n");
}
else if (i > 21){
printf("You cannot have more than twenty letters\n");
}
for (i = 0; i < 20; i++) {
if ((x[i] >= 'a') && (x[i] <= 'z')) {
printf("You many only have capital letters.\n");
capitalLetterCheck = 2;
}
}
if (capitalLetterCheck != 2) {
for (i = 0; i < 20; i++) {
if ((x[i] >= 'A') && (x[i] <= 'Z')) {
puts(x);
fillS1(y);
printf("Enter a character to replace occuring letters.\n");
while ((z = getchar() != '\n')) {
}
strFilter(y, x, z);
break;
}
}
}
printf("Would you like to enter another string?\n");
gets(&loopContinue);
} while (loopContinue != 'n');
}
void strFilter(char a[], char b[], char c){
int i = 0;
int n = 0;
while (n < 20) {
for (i = 0; i < 40; i++) {
if (a[i] == b[n]){
a[i] = c;
}
}
i = 0;
n++;
}
puts(a);
}
Thank you.
first of all please try to make your code a little easier to read, and I'm not talking about indenting but about its flow.
Also, your example output seems to work fine since there was nothing to change in any string here...?
There are a few things you should keep in mind when coding :
give your variables and functions explicit names, espcecially if you are going to have someone read your code at some point
try to keep the flow of your code simple by making small functions when you have a specifig task to execute (get the user's input, generate a random string, etc.) as opposed to just writing most of it in imbricated loops
You could also have a look at scanf (man scanf) to get the user's input
Try allocating a buffer when you get the user's input instead of having a static one that may not be of the right size
It's very easy to write some pseudo-code and then translate it into C :
WHILE someCondition
Generate a random string
Get a string from the user
Get a character from the user
Find and replace
END
Here is an example of how you could have organised your code (don't use it though - no frees, no getting the user's input, etc.) :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* generateString(void)
{
return "AEIOUYAEIOUY"; // In your implementation, this is where you'd generate the random string
}
char* getStringInput(void)
{
return "HELLO"; // In your implementation, this is where you'd get the user's string
}
char getCharInput(void)
{
return '*'; // In your implementation, this is where you'd get the user's character
}
char* findAndReplace(char* randomString, char* userString, char userChar)
{
int l1;
int l2;
int i;
int j;
char* output;
l1 = strlen(randomString);
l2 = strlen(userString);
output = (char*)malloc(sizeof(*output) * l1);
strcpy(output, randomString);
for (i = 0; i < l1; ++i)
{
for (j = 0; j < l2; ++j)
if (randomString[i] == userString[j])
output[i] = userChar;
}
return (output);
}
int main(int ac, char** av)
{
char* randomString;
char* userString;
char userChar;
char* outputString;
randomString = generateString();
userString = getStringInput();
userChar = getCharInput();
outputString = findAndReplace(randomString, userString, userChar);
printf("Result: %s\n", outputString);
// don't forget to free any allocated buffer
return (1);
}
How much debugging have you done? Try putting some printfs in your code to see what happens - when functions are called, what are your variable's values, etc.
Example :
void fillS1(char x[])
{
printf("-- entering fillS1, buffer value: %s\n", x);
for (int i = 0; i < 40; i++)
x[i] = 'A' + random() % 26;
x[40] = (char)0;
printf("-- leaving fillS1, buffer value: %s\n", x);
}
(be careful about what's in your buffer before you use printf)
This should tell you pretty quickly what's going wrong.
For example, try checking the value of "c" in strFilter when it's called, and have a second look at how you get the user's input.

C code to convert hex to int

I am writing this code to convert a hex entry into its integer equivalent. So A would be 10 and B would be 11 etc. This code acts weirdly, in that it seg. faults at random locations and including an extra newline character at times will get it to work. I am trying to debug it, just so I can understand what I am doing wrong here. Can anyone take a look and help me here ? Thanks a lot for your time.
/* Fixed working code for anyone interested */
#include <stdio.h>
#include <stdlib.h>
unsigned int hextoint(const char temp[])
{
int i;
int answer = 0;
int dec;
char hexchar[] = "aAbBcCdDeEfF" ;
for ( i=0; temp[i] != '\0'; i++ )
{
if ( temp[i] == '\0')
{
return ;
}
if (temp[i] == '0' || temp[i] == 'x' || temp[i] == 'X' )
{
printf("0");
answer = temp[i];
}
// compare each temp[i] with all contents in hexchar[]
int j;
int a = temp[i];
for ( j=0; hexchar[j] != '\0'; j++)
{
if ( temp[i] == hexchar[j] )
{
answer *= 16;
answer = answer + 10 + (j/2);
// printf("%d\n",answer );
break;
}
}
}
return answer;
}
main()
{
char *test[] =
{ "bad",
"aabbdd"
"0100",
"0x1",
"0XA",
"0X0C0BE",
"abcdef",
"123456",
"0x123456",
"deadbeef",
"zog_c"
};
int answer=0;
// Calculate the number of char's.
int numberOfChars;
numberOfChars = sizeof test /sizeof test[0];
printf("main():Number of chars = %d\n",numberOfChars);
int i;
// Go through each character and convert Hex to Integers.
for ( i = 0; i<numberOfChars;i++)
{
// Need to take the first char and then go through it and convert
it.
answer = hextoint(test[i]);
printf("%d\n",answer );
}
}
Let's take a look.
unsigned int hextoint(const char temp[])
{
int i;
int answer = 0;
char hexchar[] = "aAbBcCdDeEfF" ;
for ( i=0; temp[i] != '\0'; i++ )
{
printf("In here");
printf("%c\t",temp[i] );
}
return answer;
}
This doesn't seem to even try to do any conversion. It should always return 0, since answer is never assigned any other value. Normally, you'd do something like:
for (i=0; input[i] != '\0'; i++) {
answer *= 16;
answer += digit_value(input[i]);
}
return answer;
Where digit_value (obviously enough) returns the value of an individual digit. One way to do this is:
int digit_value(char input) {
input = tolower(input);
if (input >= '0' && input <= '9')
return input - '0';
if (input >= 'a' && input <= 'f')
return input - 'a' + 10;
return -1; // signal error.
}
Then, looking at main:
main()
{
Depending on the "implicit int" rule is generally poor practice, at least IMO. It's much better to specify the return type.
// Calculate the number of char's.
int numberOfChars;
numberOfChars = sizeof test /sizeof test[0];
This actually calculates the number of strings, not the number of chars.
for ( i = 0; i<=numberOfChars;i++)
Valid subscripts run from 0 through the number of items - 1, so this attempts to read past the end of the array (giving undefined behavior).
This'll work for any number within the unsigned int range, the nice thing is it does not use any other library functions so it is great for micro-controllers where space is tight.
unsigned int hexToInt(const char *hex)
{
unsigned int result = 0;
while (*hex)
{
if (*hex > 47 && *hex < 58)
result += (*hex - 48);
else if (*hex > 64 && *hex < 71)
result += (*hex - 55);
else if (*hex > 96 && *hex < 103)
result += (*hex - 87);
if (*++hex)
result <<= 4;
}
return result;
}
The problem is with calculating numberOfChars part. sizeof test is actually the size of the pointer, not the total length of all characters in your array, so the number returned in your code would be 1, which makes the for loop go to the second index of test (test[1]) which does not have a \0 at the end. Try using strlen for calculating numberOfChars.
This may not me the most optimal method, but it should work without problem.
unsigned int hex_to_int(const char* hex) {
unsigned int result = 0;
size_t len = strlen(hex);
for (size_t i = 0; i < len; ++i) {
char cur_char = tolower(hex[len - i - 1]);
// direct return if encounter any non-hex character.
if (!(isdigit(cur_char) && (cur_char >= 'a' && cur_char <= 'f'));)
return result;
unsigned int char_val = (isdigit(cur_char) ? cur_char - '0' : 10 + cur_char - 'a');
result += round(pow(16, i)) * char_val;
}
return result;
}

Resources