Getting jargon before actual data when printing char pointer - c

I'm writing a program that implements the Alberti Cipher, and when testing, the final print always gives a string of jargon before the actual encryption. Right now its printing \x80\x16G\xbf\xfe\x7fKHOORZRUOG, with KHOOR..... being the actual encryption. Any help appreciated :)
#include <stdio.h>
#include <stdlib.h>
int letterToNumber(char letter){
char str[2] = { letter };
int num = strtol( str, NULL, 36 ) - 10;
return num;
}
int getSize (const char * s) {
const char * t;
int size = 0;
for (t = s; *t != '\0'; t++) {
size++;
}
return size;
}
char numToChar(int numInp){
numInp=numInp+65;
char returnChar=(char)numInp;
return returnChar;
}
void encrypt_alberti(const char *message,const char *inner_ring, int initialShift,int periodicShift,int periodLength,char **result){
//sets initial shift
int numArray[25];
int count=0;
int shiftCount=0;
for(int i = 0; i < 26; ++i) {
numArray[i]=(i+initialShift)%26;
}
//encrypts each character and prints
int messageSize=getSize(message);
char encryptedMessage[messageSize];
for(int i=0; i<messageSize;i++){
count++;
if(periodicShift!=0){
if(count%periodicShift==0){
shiftCount++;
}
}
else{
periodLength=0;
}
char toBeEncrypted=message[i];
int charNumber=letterToNumber(toBeEncrypted);
int encryptedNum=numArray[(charNumber+(shiftCount*periodLength))%26];
char encryptedChar=numToChar(encryptedNum);
strncat(encryptedMessage, &encryptedChar, 1);
}
char* p1=malloc(sizeof(encryptedMessage));
strcpy(p1,encryptedMessage);
*result=p1;
}
void main(void) {
const char *example_message = "HELLOWORLD";
const char *example_inner = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *encrypted_message = NULL;
encrypt_alberti(example_message, example_inner, 3, 0, 1, &encrypted_message);
printf("message is %s\n", encrypted_message);
printf("-----------------");
free(encrypted_message);
}
}

Related

Reading a csv file in c

I'm trying to read a csv file that contains 9 columns each having information about a person. I'm supposed to store the data in a hash table and create a function to look up data based on the surname. This is my code
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
#define tablesize 27
#define entries 21
unsigned long int collisions = 0;
typedef struct {
char id[20];
char depid[10];
char surname[20];
char forename[20];
char age[2];
char ptype[20];
char gender[6];
char nation[20];
char religion[20];
char occupation[20];
}dict;
dict* hashTable[tablesize]= {NULL};
unsigned long int hash_function(char* s){
unsigned long int hash = 0;
while(*s){
hash = hash + *s;
s++;
}
return hash%tablesize;
}
void print_table(){
for(unsigned long int i=0;i<tablesize;i++){
if(hashTable[i]==NULL){
printf("%d\t---\t---\n",i);
}
else{
printf("%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",i,hashTable[i]->id,hashTable[i]->depid,hashTable[i]->surname,hashTable[i]->forename,hashTable[i]->age
,hashTable[i]->ptype,hashTable[i]->gender,hashTable[i]->nation,hashTable[i]->religion,hashTable[i]->occupation);
}
}
}
void insert(dict *d){
unsigned long int ind = hash_function(d->surname);
for(unsigned long int i=0;i<tablesize;i++){
unsigned long int try = (ind+i)%tablesize;
if(hashTable[try]==NULL){
hashTable[try] = d;
return;
}
else{
collisions++;
}
}
}
void printvalues(unsigned long int i){
printf("%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",i,hashTable[i]->id,hashTable[i]->depid,hashTable[i]->surname,hashTable[i]->forename,hashTable[i]->age
,hashTable[i]->ptype,hashTable[i]->gender,hashTable[i]->nation,hashTable[i]->religion,hashTable[i]->occupation);
}
void search(char* name){
unsigned long int ind = hash_function(name);
unsigned long int f=1;
for(unsigned long int i=0;i<tablesize;i++){
unsigned long int try = (ind+i)%tablesize;
if(hashTable[try]!=NULL&&strcmp(hashTable[try]->surname,name)==0){
printvalues(try);
f=0;
}
}
if(f==1)
printf("%s not in table\n",name);
return;
}
int main(){
FILE *fp = fopen("truncated.csv","r");
if(!fp){
printf("Error");
return 0;
}
char buff[1024];
unsigned long int row = 0, column = 0;
dict values[entries];
unsigned long int i=0;
while(fgets(buff,1024,fp)){
column=0;
row++;
if(row==1){
continue;
}
char *field = strtok(buff,",");
while(field){
if(column==0){
strcpy(values[i].id,field);
}
if(column==1){
strcpy(values[i].depid,field);
}
if(column==2){
strcpy(values[i].surname,field);
}
if(column==3){
strcpy(values[i].forename,field);
}
if(column==4){
strcpy(values[i].age,field);
}
if(column==5){
strcpy(values[i].ptype,field);
}
if(column==6){
strcpy(values[i].gender,field);
}
if(column==7){
strcpy(values[i].nation,field);
}
if(column==8){
strcpy(values[i].religion,field);
}
if(column==9){
strcpy(values[i].occupation,field);
}
field = strtok(NULL,",");
column++;
}
i++;
}
fclose(fp);
for(unsigned long int i=0;i<entries;i++){
insert(&values[i]);
}
//printvalues(values);
//print_table();
while(1){
printf("Enter term to get frequency or type 'quit' to escape:");
char name[20];
scanf("%s",name);
if(strcmp(name,"quit")==0)
return 0;
search(name);
}
return 0;
}
The problem I'm facing is that i have two csv files, one containing 60000 entries and one containing only 21 entries. When i read the smaller file, the code works just fine. But i am getting no output whatsoever for the bigger file. Any ideas? Thanks in advance.
In your code, you have only space for 21 entries (line #define entries 21)
So you'll parse 22th line and more in the big file, you'll try to write into a forbidden place. From this point, you enter in UB zone.
Solution: make values dynamic.
int count = 0;
dict *values = NULL;
while(fgets(buff,1024,fp)){
++count;
dict * tmp = realloc(values, sizeof (dict) * count);
if (NULL == tmp) {
perror("realloc");
free(values);
exit(1);
} else {
values = tmp;
}
and after the while loop:
free(values);

How to convert array of char into array of int?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stats.h"
/* Size of the Data Set */
#define SIZE (40)
void print_array (unsigned char *p, int l) {
int i;
for (i=0;i<l;i++) {
printf("%d\t",*p);
p++;
}
}
void print_array_int (int *p, int l) {
int i;
for (i=0;i<l;i++) {
printf("%d\t",*p);
p++;
}
}
void typecasting(unsigned char test[SIZE], int array[SIZE]) {
int i=0;
unsigned char *token = strtok(test,",");
while (token) {
if(i<SIZE) {
array[i++] = atoi(token);
}
token = strtok(NULL,",");
}
}
void main() {
int array[SIZE] = {};
unsigned char test[SIZE] = {34,201,190,154,8,194,2,6,114,88,45,76,123,87,25,23,200,122,150,90,92,87,177,244,201,6,12,60,8,2,5,67,7,87,250,230,99,3,100,90};
/* Other Variable Declarations Go Here */
/* Statistics and Printing Functions Go Here */
print_array(test, SIZE);
typecasting(test,array);
print_array_int(array,SIZE);
}
What I want in this code is to convert the array of char into an array of int.
Previously I tried doing this by using pointers but didn't work and it showed stack smashing error. I want to convert this array of char into array of int to perform some mathematical operations.
You are trying too hard. Here's how typecasting should look
void typecasting(unsigned char test[SIZE], int array[SIZE]) {
for (int i = 0; i < SIZE; ++i)
array[i] = test[i];
}
Your code might be suitable if you were converting from a C string, i.e. if your original test array was
char test[] = "34,201,190,154,8,194,2,6,114,88,45,76,123,87,25,23,...";
So I guess you could say you're misunderstanding the nature of char (and unsigned char) in C++. They can represent character data as in char greeting[] = "hello"; or they can represent small integers as in char test[] = {1,2,3};.

Dictionary made with C but misleading search

While I was making a dictionary using C it showed me the meaning of the word which is not present in the dictionary itself. I checked the function for checking the equality of two strings and its working fine but when I implement that function in the lookup function of the dictionary where it searches for the word shows me the meaning of the word it is not working as I intended it to do. I am not looking for a good performance I was just revising my basics in the function and simple boolean functions.
Here is the Code:
struct Entry
{
char word[50];
char defination[500];
};
bool isEqualString(const char str1[], const char str2[])
{
bool flag = true;
int i;
for(i = 0; str1[i] != '\0'; i++)
if (str1[i] == str2[i])
{
flag = true;
}
if ((str1[i] == str2[i]) && str1[i] == '\0')
flag = true;
else
flag = false;
return flag;
}
int Lookup(const struct Entry dictionary[], const char search[], int entries)
{
int i;
bool isEqualString(const char str1[], const char str2[]);
for (i = 0; i < entries; i++)
{
if (isEqualString(search, dictionary[i].word))
{
printf("%d and its indice = %d\n", isEqualString(search, dictionary[i].word), i);
return i;
}
}
return -1;
}
void main()
{
struct Entry dictionary[2] =
{ {"Hello", "It means hi."},
{"Dead", "It means you are dead"} };
int Lookup(const struct Entry dictionary[], const char search[], int entries);
int entries = 2, searchEntry;
char searchWord[10];
printf("Give us a word to find in the dictionary: \n");
scanf("%s", searchWord);
searchEntry = Lookup(dictionary, searchWord, entries);
if (searchEntry != (-1))
printf("\n%s %s", dictionary[searchEntry].word, dictionary[searchEntry].defination);
}
the logic in this function:
bool isEqualString(const char str1[], const char str2[])
is not quite right.
Suggest:
#include <stdbool.h>
#include <string.h>
bool isEqualString(const char str1[], const char str2[])
{
bool flag = true;
for( size_t i = 0; i < (strlen(str1)+1); i++ )
{
if ( str1[i] != str2[i] )
{
flag = false;
break;
}
}
return flag;
}

Cut out section of a string with another string

I got this part of a C program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char *mRNA = spleissen("AUAGUAAAAGCUCUGUUUAGGAGA", "GU", "AG");
printf("mRNA: %s\n", mRNA);
free(mRNA);
return 0;
}
I have to write the function spleissen which should work like this: it cuts out a string which goes from a GU to an AG and everything in between those two. So the program output is:
mRNA: AUACUCUGAGA
I don't really know how I can cut those parts out.
I am not allowed to use includes other than stdio, string and stdlib.
char *spleissen(const char *src, const char *start, const char *end){
size_t len = strlen(src);
char *s, *e, *ret, *work;
ret = work = malloc(len + 1);
strcpy(work, src);
len = strlen(end);
while(s = strstr(work, start)){
if((e = strstr(s, end))==NULL)
break;//delete upto last?
memmove(s, e + len, strlen(e+len)+1);
work = s;
}
return ret;
}
I think you can simply do this:
char *spleissen(char *array, char *G, char *A)
{
int l=strlen(array);
int i, j=0;
char returnstr[10010];
int b=0;
for(i=0; i<l; i++)
{
if(G[0]==array[i] && G[1]==array[i+1])
{
b=1, i++;
continue;
}
else if(A[0]==array[i] && A[1]==array[i+1] && b==1)
{
b=0, i++;
continue;
}
if(b==0)
{
returnstr[j]=array[i];
j++;
}
}
return returnstr;
}

Reversing a string in c with recursion

I have written code to reverse a string in c... it works fine but I can't return the reversed string in the main() function.
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}
it prints the reversed string but I want the reversed string in main(). How can I do this?
Following is one way to reverse string using recursion!
#include <stdio.h>
#include <string.h>
void rev_str_recursive(char arr[], size_t iStart, size_t iLast)
{
if( iStart < iLast )
{
//swap
char temp = arr[iStart];
arr[iStart] = arr[iLast];
arr[iLast] = temp;
rev_str_recursive(arr, ++iStart, --iLast);
}
}
void main()
{
char cArray[] = {"A quick brown fox jumps over a lazy dog"};
rev_str_recursive(cArray, 0, strlen(cArray)-1);
}
You need to modify the string, i.e. the input buffer to reverse(), instead of just printing it.
Doing this recursively seems a bit obnoxious, but should of course be possible.
Basically, I guess the printing becomes an assignment, something like this:
Base: The reversal of an empty string is the empty string.
Step: The reversal of a string begins by swapping the first and last characters, then recursing over the remainder of the string.
Here is another way to reverse a string using recursion:
void reverseString(char* dest, char *src, int len) {
if (src == NULL || len == 0)
return;
reverseString(dest, src + 1, len - 1);
strncat_s(dest, len + 1, src, 1);
}
You can call like that:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STRING "Let's try this one."
#define SIZE 20
void main() {
char* src = (char*)malloc(SIZE);
char* dest = (char*)malloc(SIZE);
strcpy_s(dest, SIZE, "");
strcpy_s(src, SIZE, STRING);
reverseString(dest, src, strlen(src));
/* Do anything with dest. */
// printf("%s\n", dest);
free(src);
free(dest);
}
This code is not executable :(
You define int reverse but reverse function doesnt return any value
instead use this (using void):
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}
#include <iostream>
using namespace std;
reverse( char *str)
{
if (*str!='\0')
{
reverse(str+1);
cout<<*str;
}
//cout<<*str when i am just printing here then why this is printing after one space ??
}
int main()
{
string a ;
cin>>a;
reverse(&a[0]);
return 0;
}
a little change in Emre Can Kucukoglu's answer . . .
we can eliminate strncat_s
void revstr_rec(char *sstr, char *dstr, int len)
{
int i = 0;
if((! *sstr) || (! len) )
return;
revstr_rec(sstr + 1, dstr, len - 1);
dstr[len - 1] = *sstr;
return;
}
int main()
{
char *sstr = NULL;
char *dstr = NULL;
sstr = malloc(16);
if(! sstr) {
printf("no memory . . .\n");
return 0;
}
strcpy(sstr, "hello world !");
printf("sstr: %s\n", sstr);
dstr = malloc(16);
if(! dstr) {
printf("no memory . . .\n");
return 0;
}
revstr_rec(sstr, dstr, strlen(sstr));
printf("dstr(recursive): %s\n", dstr);
free(sstr);
free(dstr);
return 0;
}
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX], *rev;
scanf("%s", str);
rev = reverse(str);
printf("The reversed string is : %s\n", rev);
return 0;
}
char *reverse(char ch[])
{
static char r[MAX];
static int i=0;
if(*ch == '\0') return "";
else
{
reverse(ch+1);
r[i++]=*ch;
}
return r;
}
A simple way with left and right index
void main()
{
char* str = (char*)malloc(strlen("somestring")+1);
strcpy(str, "somestring");
int leftIndex = 0;
int rightIndex = strlen(str) - 1;
printf("%s\n", ReverseString(str, leftIndex, rightIndex));
free(str);
}
char* ReverseString(char* str, int leftIndex, int rightIndex)
{
if (leftIndex == rightIndex || leftIndex == (rightIndex +1)) {
return str;
}
// flip letters
char leftLetter = *(str + leftIndex);
char rightLetter = *(str + rightIndex);
*(str + leftIndex) = rightLetter;
*(str + rightIndex) = leftLetter;
return ReverseString(str, leftIndex+1, rightIndex -1);
}
use sprintf it will print your reversed string into buffer.
#include<stdio.h>
char *b;
main()
{
char a[17]="abcdefg";
char buffer[17];
buffer[0]= '\0';
b = buffer;
reverse(a);
printf("%s\n",buffer);
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
sprintf(b,"%c",*a);
b++;
}
}
void palindromo(char *s)
{
if(s[0] != '\0'){
palindromo(s+1);
printf("%c", s[0]);
}
}
This is a small recursive function who print the string inverted.
#include<stdio.h>
#include<string.h>
void rev(char *);
int main()
{
char s[]="Hello";
printf("\n%s",s);
rev(s);
printf("\n%s",s);
return 0;
}
void rev(char *s)
{
static int i=0;
static int j=0;
if(j==0) //since static variable can be intitialized
{ //only with a constant literal,to store
j=strlen(s)-1; //length-1 in 1st function call, we can use
} //this trick.(condition satisfied only in 1st
//function call)
if(i<j)
{
char temp;
temp=s[i];
s[i]=s[j]; //Analogous to for(i=0,j=l-1;i<j;i++,j--)
s[j]=temp; // { //swap code }
i++;
j--;
rev(s);
}
}
#include<stdio.h>
void reverse(char *a);
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}

Resources