Simple Cryption Function in C - c

I want to create a simple encryption algorithm but I couldn't do it yet. When I run this program, it was typing on screen
"Name: John Nash, Cryptioned Data: John Nash, Decryptioned Data: John Nash"
How can I solve this problem? Where am I making a mistake?
#include<stdio.h>
char *ecrypt(char data[]);
char *decrypt(char data[]);
int i; // Global variable...
void main(void)
{
char name[] = "John Nash",*data_encryptioned,*data_decryption;
data_encryptioned = ecrypt(name);
data_decryption = decrypt(data_encryptioned);
printf("Name: %s, Cryptioned Data: %s, Decryptioned Data: %s\n",name,data_encryptioned,data_decryption);
}
char *ecrypt(char data[])
{
for(i=0;data[i]!='\0';i++)
{
data[i]+=i+12;
}
return &data[0];
}
char *decrypt(char data[])
{
for(i=0;data[i]!='\0';i++)
{
data[i]-=(i+12);
}
return &data[0];
}

You are printing the same buffer that's been encrypted and decrypted before you print. So either make a copy of the encrypted string or print them in steps to see the process:
printf("%s\n", name);
data_encryptioned = ecrypt(name);
printf("Cryptioned Data: %s\n",data_encryptioned);
data_decryption = decrypt(data_encryptioned);
printf("Decryptioned Data: %s\n",data_decryption);

Related

How do i put a word into an array

so this is part of a kind of menu, the only problemis that the word is not getting into the array "frase" i have already tried with frase [ ] = "the word" but idk why it wont work
if(lvl==1)
{
printf("lvl 1\n");
if (opc==1)
{
printf("Animales\n");
a = rand() %3 + 1;
printf("%d", a);
if (a=1)
frase <= "pato";
if (a=2)
frase <="ganso";
if (a=3)
frase <= "avispa";
}
if (opc==2)
{
printf("comida\n");
a = rand() %3 + 1;
if (a=1)
frase <="pasta";
if (a=2)
frase <="pizza";
if (a=3)
frase <="pastel";
}
if (opc==3)
{
printf("paises\n");
a = rand() %3 + 1;
if (a=1)
frase <="peru";
if (a=2)
frase <="brasil";
if (a=3)
frase <="egipto";
}
}
`
I suggest you solve this by modeling your data. In this case with a array of structs. Then you index into to obtain the relevant data:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main() {
struct {
const char *opc;
const char **frase;
} data[] = {
{"Animales", (const char *[]) { "pato", "ganso", "avispa" }},
{"comida", (const char *[]) { "pasta", "pizza", "pastel" }},
{"paises", (const char *[]) { "peru", "brasil", "egipto" }}
};
srand(time(0));
int opc = rand() % 3;
printf("lvl 1 %s %s\n", data[opc].opc, data[opc].frase[rand() % 3]);
return 0;
}
If you have a lot of data put the data in a file and write a function to build the struct at start-up. A special case of this approach is to store the data in a lightweight database like SQLite, then you can query for the relevant data at run-time or load it all it upon start-up.
You many no longer need to copy the frase, but if you want to use a strcpy:
char frase[100];
strcpy(frase, data[opc].frase[rand() % 3]);
Multiple things to be improved in the code. The if(a=1) should be changed to ==. Not sure what you mean by frase<="pato", strcpy or strncpy should be used. Please refer the following sample code.
void copytoarray(char *array, char *word, unsigned int len)
{
if(array == NULL || word == NULL)
{
return;
}
strncpy(array, word, len);
}
int main(void) {
char frase[15] = {'\0'};
int a, lvl =1;
int opc =1;
if(lvl==1)
{
printf("lvl 1\n");
if (opc==1)
{
printf("Animales\n");
a = rand() %3 + 1;
printf("%d\n", a);
if (a==1)
copytoarray(frase, "pato", strlen("pato"));
if (a==2)
copytoarray(frase, "ganso", strlen("ganso"));
if (a==3)
copytoarray(frase, "avispa", strlen("avispa"));
}
}
printf("Word: %s\n ",frase);
}

Use the values of an array from a function using scanf and pass it to the main function

I am trying to achieve this problem: EDITED
a. Create a program that will compute an electric bill.
b. Let the user provide the following data:
account name
address
type
previous reading
present reading
date of bill
-For residential, rate per kilowatt will be P15.50 while business is P25.75.
c. Create a subfunction for the following:
inputting of the above account details
computation of bill
display of the account information,
current consumed kilowatt and
the billing amount for the month.
d. Example Output:
Enter name: Juan Cruz
Enter address: Nasipit, Adn
Type (Residential or Business): Residential
Previous Reading: 10
Present Reading: 15
Date of Bill: March 15, 2022
Display:
Account name: Juan Cruz
Address: Nasipit, Adn
Type: Residential
Date: March 15, 2022
Previous Reading: 10
Present Reading: 15
Consumed Kilowatt: 5
Amount Billed: P77.50
Formulas: consumed_kilowatt=present_reading-previous_reading
billed_amount=consumed_kilowatt*rate_per_kilowatt
Here's the code so far.
#include <stdio.h>
#include <strings.h>
void details(char* info);
float consumed(float a, float b);
float business(float a);
float residence(float a);
void main(){
float prev, pres;
float billed_amount, consumed_kilowatt;
char* info[200];
char bus[]="Business", res[]="Residential";
char *acc_nm, *add, *type, *prevread, *presread, *date;
char account_info[25];
details(info);
prev=atof(prevread);
pres=atof(presread);
consumed_kilowatt=consumed(pres, prev);
if(!strcmp(type,bus)){
billed_amount=business(consumed_kilowatt);
} else {
billed_amount=residence(consumed_kilowatt);
}
}
void details(char* info){
char array[][20] = { "Account Name", "Address", "Type", "Previous Reading", "Present Reading", "Date"};
int i;
printf("Please provide your data by following the format: Account_Name, Address(St_Brgy_City_State), Type(Residential or Business), Previousreading, PresentReading, Date(MM/DD/YYYY)");
printf("\n\nNote: Please make sure to follow format. Avoid unnecessary spaces and symbols.\n\n");
for (i=0; i<6; i++){
printf("Enter %s: ", array[i]);
scanf("%s", &info[i]);
}
}
float consumed(float a, float b){
float read;
read=a-b;
return read;
}
float business(float a){
float business=25.75, val;
val=a*business;
return val;
}
float residence(float a){
float residence=15.50, val;
val=a*residence;
return val;
}
I am trying to use the values I collected as an array in details() within the void main() so I can compute consumed_kilowatt and billed_amount formulas.
as you can see I am new to c programming. I have been reading online resources only and I really don't have any idea where should I start learning. I found this challenge and I thought of trying this out but I can't seem to get it.
There are inconsistencies in the parameter you are passing to details. That function is declared to accept a char *, but you are passing it an array of pointers. But the function you have written seems to expect an array of char *, rather than the char * that it is defined to take. I think you are looking for something like:
#include <stdio.h>
#include <stdlib.h>
void details(char (*info)[200]);
struct column {
char header[20];
char format[40];
};
struct column c[] = {
{ "Account Name", "" },
{ "Address", " (St_Brgy_City_State)" },
{ "Type", " (Residential or Business)" },
{ "Previous Reading", "" },
{ "Present Reading", "" },
{ "Date", " (MM/DD/YYYY)" }
};
int
main(void)
{
char info[6][200];
details(info);
for( int i = 0; i < 6; i++ ){
printf("%20s: %s\n", c[i].header, info[i]);
}
}
void
details(char (*info)[200])
{
int i;
printf("%s", "Please provide your data by following the format: ");
for( i = 0; i < 6; i++ ){
printf("%s%s%s", c[i].header, c[i].format, i == 5 ? "\n" : ", ");
}
printf("Note: Please make sure to follow format. Avoid unnecessary spaces and symbols.\n\n");
for( i = 0; i < 6; i++ ){
printf("Enter %s: ", c[i].header);
if( scanf(" %199[^\n]", info[i]) != 1 ){
fprintf(stderr, "Invalid input\n");
exit(1);
}
}
}
Note that scanf is a terrible tool. You will be much happier if you abandon its use now. Learning its foibles will not help you learn the language and will merely cause hours and hours of pointless frustration.

Using Struct in C to create a library for items and giving location feedback based upon user entry. I just cant seem to find my error

//make a location marker for key items
#include <stdio.h>
#include <string.h>
struct find {int index; char name[50]; char location[50]; };
int main() {
char locate_item[50];
//using struct to add items
struct find item1;
item1.index = 1;
strcpy(item1.name, "guitar");
strcpy(item1.location, "Usually near the table in the living room area.\n");
struct find item2;
item2.index = 2;
strcpy(item2.name, "ipad");
strcpy(item2.location, "Usually on the table or charging on the bed.\n");
//using while and if statements to get user feedback and display the appropriate location
while (locate_item != item1.name || locate_item != item2.name) {
printf("what is the item you want to find? \n");
scanf("%s", locate_item);
printf("You entered %s\n", locate_item);
if (locate_item == item1.name) {
printf("%s", item1.location);
} else if (locate_item == item2.name) {
printf("%s", item2.location);
} else {
printf("Incorrect entry. Please try again.\n");
}
}
return 0;
}
locate_item != item1.name || locate_item != item2.name compares pointer, however, you want to use strcmp() to compare two strings by value. strcmp() returns 0 if the two strings are the same.
In either case, your program doesn't make a lot of sense. You probably want to find locate_item in the an array of items (renamed from find) along these lines:
#include <stdio.h>
#include <string.h>
struct item {
int index;
char name[50];
char location[50];
};
int main() {
struct item items[] = {
{ 1, "guitar", "Usually near the table in the living room area." },
{ 2, "ipad", "Usually on the table or charging on the bed." },
{ 0 }
};
for(;;) {
printf("what is the item you want to find? \n");
char locate_item[50];
scanf("%s", locate_item);
//printf("You entered %s\n", locate_item);
for(int i = 0; items[i].name[0]; i++) {
if(!strcmp(items[i].name, locate_item)) {
printf("%s\n", items[i].location);
goto done;
}
}
printf("Incorrect entry. Please try again.\n");
}
done:
return 0;
}

Python's binascii.unhexlify function in C

I'm building a program that takes input as if it is a bare MAC address and turn it into a binary string. I'm doing this on a embedded system so there is no STD. I have been trying something similar to this question but after 2 days I haven't achieved anything, I'm really bad with these kind of things.
What I wanted is output to be equal to goal, take this into consideration:
#include <stdio.h>
int main() {
const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
printf("Goal: %s\n", goal);
char* input = "aabbccddeeff";
printf("Input: %s\n", input);
char* output = NULL;
// Magic code here
if (output == goal) {
printf("Did work! Yay!");
} else {
printf("Did not work, keep trying");
}
}
Thanks, this is for a personal project and I really want to finish it
First, your comparison should use strcmp else it'll be always wrong.
Then, I would read the string 2-char by 2-char and convert each "digit" to its value (0-15), then compose the result with shifting
#include <stdio.h>
#include <string.h>
// helper function to convert a char 0-9 or a-f to its decimal value (0-16)
// if something else is passed returns 0...
int a2v(char c)
{
if ((c>='0')&&(c<='9'))
{
return c-'0';
}
if ((c>='a')&&(c<='f'))
{
return c-'a'+10;
}
else return 0;
}
int main() {
const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
printf("Goal: %s\n", goal);
const char* input = "aabbccddeeff";
int i;
char output[strlen(input)/2 + 1];
char *ptr = output;
for (i=0;i<strlen(input);i+=2)
{
*ptr++ = (a2v(input[i])<<4) + a2v(input[i]);
}
*ptr = '\0';
printf("Goal: %s\n", output);
if (strcmp(output,goal)==0) {
printf("Did work! Yay!");
} else {
printf("Did not work, keep trying");
}
}

how to best achieve string to number mapping in a c program

I have a definite set of strings and its corresponding numbers:
kill -> 1
live -> 2
half_kill -> 3
dont_live -> 4
List is of 30 such strings and their number mapping.
If user enters "kill", I need to return 1 and if he enters "dont_live" I need to return 4.
How should I achieve this in c program? I am looking for an efficient solution because this operation needs to be done 100s of times.
should I put them in #define in my .h file?
Thanks in advance.
Sort your table, and use the standard library function bsearch to perform a binary search.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct entry {
char *str;
int n;
};
/* sorted according to str */
struct entry dict[] = {
"dont_live", 4,
"half_kill", 3,
"kill", 1,
"live", 2,
};
int compare(const void *s1, const void *s2)
{
const struct entry *e1 = s1;
const struct entry *e2 = s2;
return strcmp(e1->str, e2->str);
}
int
main (int argc, char *argv[])
{
struct entry *result, key = {argv[1]};
result = bsearch(&key, dict, sizeof(dict)/sizeof(dict[0]),
sizeof dict[0], compare);
if (result)
printf("%d\n", result->n);
return 0;
}
Here's what you get when you run the program.
$ ./a.out kill
1
$ ./a.out half_kill
3
$ ./a.out foo
<no output>
PS: I reused portions of sidyll's program. My answer should now be CC BY-SA compliant :p
A possible solution:
#include <stdio.h>
#include <string.h>
struct entry {
char *str;
int n;
};
struct entry dict[] = {
"kill", 1,
"live", 2,
"half_kill", 3,
"dont_live", 4,
0,0
};
int
number_for_key(char *key)
{
int i = 0;
char *name = dict[i].str;
while (name) {
if (strcmp(name, key) == 0)
return dict[i].n;
name = dict[++i].str;
}
return 0;
}
int
main (int argc, char *argv[])
{
printf("enter your keyword: ");
char s[100]; scanf("%s", s);
printf("the number is: %d\n", number_for_key(s));
return 0;
}
Here's one approach:
int get_index(char *s)
{
static const char mapping[] = "\1.kill\2.live\3.half_kill\4.dont_live";
char buf[sizeof mapping];
const char *p;
snprintf(buf, sizeof buf, ".%s", s);
p = strstr(mapping, buf);
return p ? p[-1] : 0;
}
The . mess is to work around kill being a substring of half_kill. Without that issue you could simply search for the string directly.
If it is a very short list of strings then a simple block of ifs will be more than sufficient
if (0 == strcmp(value, "kill")) {
return 1;
}
if (0 == strcmp(value, "live")) {
return 2;
}
...
If the number approach 10 I would begin to profile my application though and consider a map style structure.
if you have a fixed set of strimgs, you have two options: generate a perfect hashing function (check gperf or cmph) or create a trie so that you never have to check charcters more than once.
Compilers usually use perfect hashes to recognize a language keyword, in your case I would probably go with the trie, it should be the fastest way (but nothing beats direct measurement!)
Is it really a bottleneck? You should worry about efficiency only if the simple solution proves to be too slow.
Having said that, possible speed improvements are checking the lengths first:
If it's 4 characters then it could be "kill" or "live"
If it's 9 characters then it could be "half_kill" or "dont_live"
or checking the first character in a switch statement:
switch (string[0]) {
case 'k':
if (strcmp(string, "kill") == 0)
return 1;
return 0;
case 'l':
...
default:
return 0;
}
Use hashmap/ hashtable i think this would be the best solution.
Can you use an Enumunerator?
int main(void) {
enum outcome { kill=1, live, half_kill, dont_live };
printf("%i\n", kill); //1
printf("%i\n", dont_live); //4
printf("%i\n", half_kill); //3
printf("%i\n", live); //2
return 0;
}
Create a list of const values:
const int kill = 1;
const int live = 2;
const int half_kill = 3;
etc

Resources