#include <stdio.h>
#include <string.h>
char *maskify(char *masked,const char *string);
main(void)
{
char string;
char display;
char credit[9];
printf("Enter credit card no: ");
scanf("%s", &credit);
display = maskify(credit,string);
printf("Is credit card no: %s",display);
}
char *maskify(char *masked, const char *string)
{
int n = strlen(strcpy(masked,string))- 4;
if(n > 0)memset(masked ,'#' ,n);
return masked;
}
pliz help in spotting the error
I was trying to achieve following output not for the test data but code is not working.
it bring a negative error.
sample_test("4556364607935616", "############5616");
sample_test( "64607935616", "#######5616");
sample_test( "12345", "#2345");
sample_test( "1234", "1234");
sample_test( "123", "123");
sample_test( "12", "12");
sample_test( "1", "1");
sample_test( "", "");
sample_test( "Skippy", "##ippy");
sample_test("Nananananananananananananananana Batman!", "####################################man!");
}
Related
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);
}
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.
I created a gaming platform and i wanna let trade some games.
So I managed to elaborate a code where a user can sell his games to a marketplace and another user could buy it whenever he wants, if he has credit. In order to do it, I need to add the sold game to the buyer's library and remove it from the seller's library, but there's something I'm missing.
The code I wrote is more or less:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
typedef struct {
char username [15];
char email [25];
char surname [20];
char name [20];
char sex;
int hours;
int level;
float credit;
char* library[20];
} User;
typedef struct {
char id_code [7];
char name [35];
char developer [30];
char category [15];
float price;
int pegi;
char seller [15];
} Game;
...
int main() {
int max=1, z=0, u=0;
User signed_up [max];
Game database [20], marketplace [20];
...
system("pause");
return 0;
}
...
void buy_game (int max, int *pz, int *pu, User signed_up[], Game database[], Game marketplace[]) {
int i=0, j=0, h=0, y=0, x=0, a=0, b=0, w=0, v=0, c=0;
bool game_found=false, user_found=false, not_owned_game=false;
char input_game [35], input_user[15];
v=*pz;
w=*pu;
...
printf("\n%*sInserisci username dell'utente con cui acquistare il gioco: ", 26, "");
fflush(stdin);
scanf("%s", input_user);
printf("\n");
for(i=0;i<max-1;i++) {
if (strcmp(input_user, signed_up[i].username)==0) {
user_found=true;
printf("%*sInserisci nome del gioco da acquistare: ", 26, "");
fflush(stdin);
fgets(input_game, sizeof (input_game), stdin);
input_game[strlen(input_game)-1]='\0';
printf("\n");
for (j=0;j<w;j++) {
if (strcmp(input_game, marketplace[j].name)==0) {
game_found=true;
for (h=0;h<max-1;h++) {
if (strcmp(signed_up[h].username, marketplace[j].seller)==0) {
for (y=0;y<v;y++) {
if (strcmp(marketplace[j].name, signed_up[h].library[y])==0) {
for (a=0;a<v;a++) {
if (strcmp(marketplace[j].name, signed_up[i].library[a])!=0) {
not_owned_game=true;
if (marketplace[j].price<=signed_up[i].credit) {
printf("\n%*sOperazione avvenuta con successo!\n", 26, "");
signed_up[i].credit=signed_up[i].credit-marketplace[j].price;
printf("\n%*sIl credito attuale dell'utente %s %c: EUR %.2f\n", 26, "", signed_up[i].username, 138, signed_up[i].credit);
signed_up[h].credit=signed_up[h].credit+marketplace[j].price;
printf("\n%*sIl credito attuale dell'utente %s %c: EUR %.2f\n\n\n", 26, "", signed_up[h].username, 138, signed_up[h].credit);
signed_up[i].library[y]=marketplace[j].name;
//add game to buyer's library
do {
signed_up[h].library[y]=signed_up[h].library[y+1];
y+=1;
} while (y<v-1);
signed_up[h].library[v-1]="";
//remove game from seller's library
do {
marketplace[j]=marketplace[j+1];
j+=1;
} while (j<w-1);
*pu-=1;
//remove game from marketplace
} else {
printf("%*sCredito acquirente insufficiente! Si prega di ricaricare il conto.\n\n", 26, "");
}
}
} if (not_owned_game==false) {
printf("%*sGioco inserito gi%c presente nella libreria dell'utente!\n\n\n", 26, "", 133);
}
}
}
}
}
}
} if (game_found==false) {
printf("%*sGioco inserito non presente nel marketplace!\n\n\n", 26, "");
}
}
} if (user_found==false) {
printf("\n%*sUsername inserito non presente nel database!\n\n\n", 26, "");
}
}
The issue I have is the program has a weird behaviour when I check users' libraries cause it doesn't memorize properly both buyer and seller's libraries; in fact the program refuses to show any game in their libraries.
Arrays have fixed size, so you can't remove entries. You can overwrite, and you can shift things around, either of which might result in a particular value no longer existing in the array.
So think about what you want your fixed-size array to look like when it logically contains one fewer item, because you can't actually shrink it. Then think about what changes need to be made to mutate the array to the desired state, and finally write the code.
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);
I am trying to write a console application where the user enters in a City then the program looks up the city name in a typedef structure and proceeds to display the city's latitude and longitude coordinates. I have zero errors displaying for the program, but it seems that each time I enter a city and press enter the console application will display city not found and then close out. Here is the code with a few of the cities from the typdef structure (full structure contains 200 variables).
#include <stdio.h>
#include <string.h>
#define MAX_CITY_LEN 35
typedef struct {
char name[MAX_CITY_LEN];
float latitude;
float longitude;
} PLACE_T;
PLACE_T places[] =
{{"Aberdeen,Scotland",57.15,-2.15},
{"Adelaide,Australia",-34.92,138.6},
{"Albany,NY,USA",42.67,-73.75},
{"Albuquerque,NM,USA",35.08,-106.65},
{"Algiers,Algeria",36.83,3.0},
{"Amarillo,TX,USA",35.18,-101.83},
{"Amsterdam,Netherlands",52.37,4.88},
{"Anchorage,AK,USA",61.22,-149.9},
{"Ankara,Turkey",39.92,32.92},
{"Asuncion,Paraguay",-25.25,-57.67},
{"Athens,Greece",37.97,23.72},
{"Atlanta,GA,USA",33.75,-84.38},
{"Auckland,New Zealand",-36.87,174.75},
{"",999,999}};
int main()
{
int j;
int found=0;
char city[MAX_CITY_LEN];
int citySize=(sizeof(places)/sizeof(places[0]));
printf("Please Enter the Name of a City: \n");
scanf_s("%s", &city, MAX_CITY_LEN,stdin);
city[strlen(city)-1]='\0';
for(j=0;j<citySize;j++)
{
if(strcmp(city,places[j].name)==0)
{
found=1;
printf("lat = %f, long = %f",places[j].latitude,places[j].longitude);
break;
}
}
if(!found)
printf("City not found");
return 0;
}
Thanks!
try this
int found=0;
char city[MAX_CITY_LEN];
int citySize=(sizeof(places)/sizeof(places[0]));
int j, len;
printf("Please Enter the Name of a City: \n");
scanf_s("%34s", city, MAX_CITY_LEN);
len = strlen(city);
for(j=0;j<citySize;j++){
if(strncmp(city, places[j].name, len)==0 && places[j].name[len]==','){
found=1;
printf("lat = %f, long = %f",places[j].latitude,places[j].longitude);
break;
}
}
if(!found)
printf("City not found");