My program is fairly simple.
Read the H,W, horizontal char, vertical char from a user.
And then print out the square by the given params.
However, when user type 'y' to run the second time.
the height param is always missing.
I didn't get it.
A likely buggy point i can think is that the input buffer might not clean.
Any idea?
C program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <memory.h>
const int USER_INPUT_SIZE_EACH_LINE = 999;
void draw_middle_lines(char *middle_line, int width) {
printf("%s", middle_line);
for (int i = 2; i < width; i++) {
printf(" ");
}
printf("%s\n", middle_line);
}
void draw_bound_line(char *bound_char, int width) {
for (int i = 0; i < width; i++) {
printf("%s", bound_char);
}
printf("\n");
}
void clearNewline(char *line, int max_len) {
for (int i = 0; i < max_len; i++){
printf("%c", line[i]);
}
printf("\n");
for (int i = 0; i < max_len; i++) {
if (line[i] == '\n') {
line[i] = '\0';
}
}
}
char **ask_user_preference() {
printf("\nask user preference\n");
const int NUM_OF_PROMPTS = 4;
const char *prompt[] = {
"please input height:",
"please input width:",
"please input horizontal char:",
"please input vertical char:",
};
char **preference;
preference = malloc(NUM_OF_PROMPTS);
for (int i = 0; i < NUM_OF_PROMPTS; i++) {
preference[i] = malloc(USER_INPUT_SIZE_EACH_LINE);
memset(preference[i], 0, sizeof(char) * USER_INPUT_SIZE_EACH_LINE);
printf("%s", prompt[i]);
fgets(preference[i], USER_INPUT_SIZE_EACH_LINE, stdin);
clearNewline(preference[i], USER_INPUT_SIZE_EACH_LINE);
}
return preference;
}
void draw(int w, int h, char *bound_char, char *middle_char) {
printf("width: %d\n", w);
printf("height: %d\n", h);
draw_bound_line(bound_char, w);
for (int i = 2; i < h; i++) {
draw_middle_lines(middle_char, w);
}
draw_bound_line(bound_char, w);
}
void clr_input_buffer() {
for (;;) {
int c = getchar();
if (c == EOF || c == '\n')
break;
}
}
int main() {
char *cont = malloc(10+1);
do {
char **pref = ask_user_preference();
int height = atoi(pref[0]);
int width = atoi(pref[1]);
char *bound_char = pref[2];
char *middle_char = pref[3];
draw(width, height, bound_char, middle_char);
printf("continue to play (y/n)? ");
fgets(cont, 2, stdin);
if (strncmp(cont, "y", 1) == 0) {
clr_input_buffer();
}else{
break;
}
} while (1);
printf("BYE BYE~");
return 0;
}
Related
i have written this program (its not finished, there are more functions to be added) however, I want to know why my withinBudget function is sometimes producing correct results and other times producing inaccurate results. The withinBudget works out whether or not the customer has sufficient balance or not. if it returns true it prints purchase has been successful or prints insufficient balance.
#include <stdio.h>
int isItemExist(char itemPrefixes[], char itemPrefix);
void displayMenu(char itemPrefixes[], int itemPrices[], int n);
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]);
int n;
int main() {
char itemPrefixes[5];
int itemPrices[5];
int budget = 0;
char itemPurchased;
printf("***ItemPrefixes***");
printf("\nA: Apple\n");
printf("O: Orange\n");
printf("M: Mango\n");
printf("P: Pear\n");
printf("G: Grapes\n");
printf("\n***ShopKeeperPanel***");
printf("\nHow many fruit items do you want to add to the shop?: ");
scanf_s("%d", &n);
int chosenFruitItem = 0;
while (chosenFruitItem < n) {
printf("\n(%d) Enter the item prefix: ", chosenFruitItem + 1);
char itemPrefix = ' ';
scanf_s(" %c", &itemPrefix, 1);
if (isItemExist(itemPrefixes, itemPrefix) == 1) {
printf("Error Item already exist");
continue;
}
else {
itemPrefixes[chosenFruitItem] = itemPrefix;
printf("Enter price for item (%c): ", itemPrefix);
scanf_s("%d", &itemPrices[chosenFruitItem]);
chosenFruitItem++;
}
}
displayMenu(itemPrefixes, itemPrices, n);
printf("\n**CUSTOMER PANEL***");
printf("\nWhat is your budget for today?: ");
scanf_s("%d", &budget);
printf("\nPlease enter Item Prefix from the menu to purchase: ");
scanf_s(" %c", &itemPurchased, 1);
if (withinBudget(budget, itemPurchased, itemPrefixes, itemPrices) == 1) {
printf("PURCHASS SUCCESS");
}
else
{
printf("INSUFFICENT BUDGET");
}
}
int isItemExist(char itemPrefixes[], char itemPrefix) {
for (int i = 0; i < n; i++) {
if (itemPrefixes[i] == itemPrefix) {
return 1;
}
}
return 0;
}
void displayMenu(char itemPrefixes[], int itemPrices[], int n) {
printf("\n*** ShopMenu ***");
printf("\nItem: \t Price: ");
for (int i = 0; i < n; i++) {
printf("\n%c:\t %d", itemPrefixes[i], itemPrices[i]);
}}
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]) {
for (int i = 0; i < n; i++) {
if (itemPurchased == itemPrefixes[i] && itemPrices[i] < budget)
{
return 1;
}
return 0;
}
}
the output:
Please ident your code. Either simplest mistakes could go unnoticed because of this.
Here you have an auto one.
After doing this to your code, here's the last function:
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]) {
for (int i = 0; i < n; i++) {
if (itemPurchased == itemPrefixes[i] && itemPrices[i] < budget) {
return 1;
}
return 0;
}
}
As you can see, return 0 is inside loop, it's working only if itemPurchased == itemPrefixes[0] && itemPrices[0] < budget as i will never be incremented.
So your function should be:
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]) {
for (int i = 0; i < n; i++) {
if (itemPurchased == itemPrefixes[i] && itemPrices[i] < budget) {
return 1;
}
}
return 0;
}
As stated in the title I am trying to find all lower-case letters that are not in a series of words. There are no upper-case letters, digits, punctuation, or special symbols.
I need help fixing my code. I am stuck and do not know where to go from here.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int letters[26];
char words[50];
int i = 0, b = 0;
printf("Enter your input : ");
scanf("%s", words);
for(i = 0; i < 26; i++){
letters[i] = 0;
}
while(!feof(stdin)){
for(b = 0; b < strlen(words) - 1; b++){
letters[ words[b] - 'a']++;
scanf("%s", words);
}
}
printf("\nMissing letters : %c ", b + 97);
return 0;
}
My output is giving me some random letter that I do not know where it is coming from.
Here is a working first implementation.
As well as the comments that have already been made, you should use functions wherever possible to separate out the functionality of the program into logical steps. Your main function should then just call the appropriate functions in order to solve the problem. Each function should be something that is self contained and testable.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_INPUT 20 /* Max input to read from user. */
char *readinput(void);
void find_missing_lower_case(char *, int);
int main()
{
char *user_input = readinput();
int len_input = strlen(user_input);
printf("user input: %s\n", user_input);
printf("len input: %d\n", len_input);
find_missing_lower_case(user_input, len_input);
/* Free the memory allocated for 'user_input'. */
free(user_input);
return 0;
}
char *readinput()
{
char a;
char *result = (char *) malloc(MAX_INPUT);
int i;
for(i = 0; i < MAX_INPUT; ++i)
{
scanf("%c", &a);
if( a == '\n')
{
break;
}
*(result + i) = a;
}
*(result + i) = '\0';
return result;
}
void find_missing_lower_case(char *input, int len_input)
{
int a = 97; /* ASCII value of 'a' */
int z = 122; /* ASCII value of 'z' */
int lower_case_chars[26] = {0}; /* Initialise all to value of 0 */
/* Scan through input and if a lower case char is found, set the
* corresponding index of lower_case_chars to 1
*/
for(int i = 0; i < len_input; i++)
{
char c = *(input + i);
if(c >= a && c <= z)
{
lower_case_chars[c - a] = 1;
}
}
/* Iterate through lower_case_chars and print any values that were not set
* to 1 in the above for loop.
*/
printf("Missing lower case characters:\n");
for(int i = 0; i < 26; i++)
{
if(!lower_case_chars[i])
{
printf("%c ", i + a);
}
}
printf("\n");
}
I figured it out and this is the code I used.
int main(void)
{
int array[26];
char w;
int i=0;
for(i=0; i<26; i++) {
array[i]=0; }
printf("Enter your input: ");
scanf("%c", &w);
while(!feof(stdin)) {
array[w-97] = 1;
scanf("%c", &w); }
printf("Missing letters: ");
for(i=0; i<26; i++) {
if(array[i] == 0) {
printf("%c ", i+97); }
}
printf("\n");
return 0;
}
Below is a program called scrabble.c that is being used to play a simplified version of the game. The user is dealt 7 random characters and then told to enter a word using those characters. The program should check if the user then uses the letters given in order to create a valid word. I am having a problem with the function that checks to see if the user enters a valid word.
#include <stdio.h>
#include <time.h>
#include <stdbool.h>
#define SIZE_LETTER_SET 100
#define SIZE_CHOOSEN_LETTER 7
void generate_letter_set(int letter_set[7], int size_letter_set, int
num_letters)
{
//num_letters should be 7
//size_letter_set should be 100
bool choosen[SIZE_LETTER_SET] = {false};
int group[SIZE_LETTER_SET] =
{'A','A','A','A','A','A','A','A','A','B','B','C','C','D','D','D','D','E','E','E','E','E','E','E','E','E','E','E','E','F','F','G','G','G','H','H',
'I','I','I','I','I','I','I','I','I','J','K','L','L','L','L','M','M','N','N','N','N','N','N','O','O','O','O','O','O','O','O','P','P','Q','R','R','R','R','R','R','S','S',
'S','S','T','T','T','T','T','T','U','U','U','U','V','V','W','W','X','Y','Y','Z',' ',' '};
int c, letter, letterfound;
srand((unsigned) time(NULL));
for(c = 0; c < num_letters; c++)
{
letterfound = 1;
while(letterfound % 2 != 0)
{
letter = rand() % 100;
if(choosen[letter] == false)
{
letter_set[c] = group[letter];
choosen[letter] = true;
letterfound++;
}
}
}
printf("Your letters are: ");
for(c = 0; c < num_letters; c++)
{
printf("%c ", letter_set[c]);
}
printf("\n");
return;
}
int read_word(char word[], int max_size_word)
{
int c = 0, input_count = 0;
printf("Please enter your word : ");
char user_input = getchar();
for(c = 0; c < max_size_word; c++)
{
if(user_input != '\n')
{
word[c] = user_input;
input_count++;
//printf("input_count = %d, letter entered = %c\n", input_count,
user_input);
}
else if(user_input == '\n')
{
return input_count;
}
user_input = getchar();
}
return input_count;
}
This function is where the error occurs, the function should check if the user is using their 7 letters to create a valid word.
_Bool check_word (char word[], int size_word, int letter_set[], int
size_letter_set)
{
printf("beginning word check : \n");
int c = 0;
int b = 0;
int dup_count = 0;
int pair_found = 0;
for(c = 0; c < size_word; c++);
pair_found = 1;
for(b = 0; b < size_letter_set; b++)
{
printf("Checking if %c is equal to %c", word[c], letter_set[b]);
if((toupper(word[c])) == letter_set[b])
{
letter_set[b] = 0;
dup_count++;
pair_found++;
}
}
printf("Total duplicates = %d : check word is ", dup_count);
if((dup_count >= size_word))
{
printf("true");
return true;
}
else
{
printf("false");
return false;
}
}
int main(void)
{
int letter_set[7] = {0};
char word[7] = {0};
int size_letter_set = 100;
int num_letters = 7;
generate_letter_set(letter_set, size_letter_set, num_letters);
int size_word = read_word(word, num_letters);
check_word(word, num_letters, letter_set, size_letter_set);
return 0;
}
I am having trouble doing my homework.
I am doing an RSA application which can encrypt and decrypt.
The problem is that after I Input things to encrypt the results are weird and I can't decrypt anything. This is because when I copied the results of encryption which are symbols, I got more weird stuffs.
I'm guessing it has something to do with my formula getting negative ASCIIs as results.
Below is what I tried, and, in order to understand what I meant by weird, just compile and try it out(I have some unused stuffs which I haven't removed yet):
Output:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define boolean int
#define true 1
#define false 0
//===================================================//
int p = 0;
int q = 0;
int n = 0;
int m = 0;
int divider = 2;
int tempdivider = 2;
int initial = 0;
int x = 0;
int y = 0;
char msg[100];
char alphabet[27];
//===================================================//
void cls();
void menu();
void init();
void reinit();
void inputencrypt();
//int encrypt(int num);
void encrypt();
char decrypt(char text[]);
int fpb(int num);
int d(int num);
int primecheck(int a);
boolean checkdigit(char text[]);
//===================================================//
int main() {
frontpage();
init();
menu();
getchar();
return 0;
}
//===================================================//
void cls() {
for (int i = 0;i < 25;i++) {
printf("\n");
}
}
//===================================================//
boolean checkdigit(char text[]) {
int len = strlen(text);
for (int i = 0;i < len;++i) {
if (text[i]<'0' || text[i]>'9') {
return false;
}
}
return true;
}
int primecheck(int a) {
if (a == 1) {
return false;
}
for (int i = 2;i < a;i++) {
if (a%i == 0) {
return false;
}
}
return true;
}
//===================================================//
void reinit() {
for (int i = 1;i < 27;i++) {
alphabet[i] = 'a' + i - 1;
}
p = 0;
q = 0;
n = 0;
m = 0;
divider = 2;
tempdivider = 2;
initial = 120;
x = 0;
y = 0;
}
void init() {
reinit();
do {
printf("p = ");
scanf("%d", &p);fflush(stdin);
if (!primecheck(p)) {
printf("must be prime number! \n");
}
} while (!primecheck(p));
do {
printf("q = ");
scanf("%d", &q);fflush(stdin);
if (!primecheck(q)) {
printf("must be prime number! \n");
}
} while (!primecheck(q));
n = p*q;
m = (p - 1)*(q - 1);
initial = m;
x = fpb(m);
y = d(m);
printf("n = %d\n", n);
printf("m = %d\n", m);
printf("e = %d\n", x);
printf("d = %d\n", y);
system("pause");
}
//===================================================//
void menu() {
char input[2];
int input1 = 0;
do {
do {
cls();
printf("main menu\n");
printf("================\n");
printf("1. encrypt\n");
printf("2. decrypt\n");
printf("3. exit\n");
printf(">> ");
scanf("%s", input);fflush(stdin);
if (checkdigit(input)) {
input1 = atoi(input);
}
} while (!checkdigit(input));
switch (input1) {
case 1:
int c;
char encrypted[100];
char word[100];
printf("input word to encrypt : ");
scanf(" %[^\n]", word);fflush(stdin);
for (int i = 0;i < strlen(word);i++) {
if (word[i] == ' ') {
encrypted[i] = ' ';
//i++;
}
else {
for (int j = 1;j < 27;j++) {
if (word[i] == alphabet[j]) {
c = 0;
c = pow(j, x);
c = c%n;
encrypted[i] = c;
break;
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", word[i]);
}
printf(" ]\n");
printf("\n\nEncrypted ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", encrypted[i]);
}
printf(" ]\n");
printf("\n\nEncrypted [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%c", encrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
case 2:
int temp[100];
char decrypted[100];
char wordx[100];
int h;
printf("input word to decrypt : ");
scanf(" %[^\n]", wordx);fflush(stdin);
for (int i = 0;i < strlen(wordx);i++) {
temp[i] = wordx[i];
//temp[i] -= 97;
//printf("%d ::: %c\n", temp[i], temp[i]);
}
for (int i = 0;i < strlen(wordx);i++) {
if (wordx[i] == ' ') {
decrypted[i] = ' ';
}
else {
h = 0;
h = pow(temp[i], y);
h = h%n;
decrypted[i] = h;
for (int j = 1;j < 27;j++) {
if (decrypted[i] == j) {
decrypted[i] = alphabet[j];
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", wordx[i]);
}
printf(" ]\n");
printf("\n\nDecrypted ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", decrypted[i]);
}
printf(" ]\n");
printf("\n\nDecrypted [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", decrypted[i]);
printf("%c", decrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
}
} while (input1 != 3);
}
//===================================================//
int fpb(int num) {
if (!primecheck(num)) {
if (num%divider == 0) {
num = num / divider;
divider = 2;
}
else {
divider++;
}
fpb(num);
}
else if (primecheck(num)) {
if (!primecheck(num + divider)) {
tempdivider++;
divider = tempdivider;
num = initial;
fpb(num);
}
else {
return num + divider;
}
}
}
int d(int num) {
for (int i = 1;i < num;i++) {
if ((x*i) % num == 1) {
return i;
}
}
}
You have a general comprehension problem. Your console is only able to represent 96 characters correctly (known as printable 7bit-ASCII characters, 0x20 to 0x7F), but a byte can hold 255 different values. Your encryption algorithm does not care about this limited range, it will encrypt any value in the range [0..255] into another value in the range [0..255]. So your ASCII input characters will most likely be encrypted into values that cannot be represented by your console correctly. Copy&Past will not work correctly for non-printable characters (like 0x0B, which is a tab).
But now you will wonder: Why does that work for e.g. E-Mails? Simply: Because those characters are converted into an ASCII representation. Please google a bit for Base64 encoding.
As an alternative, you can always stream your encrypted characters into a file and later read back from that. This way you will bypass the limitations of your console.
Btw: Please have a look at the documentation of printf() and you will know, why you get those negative values.
The encrypt option has these three statements consecutively
c = 0;
c = pow(j, x);
c = c%n;
and the last of those will leave c in the range 0..(n-1).
Apart from that, there is no else clause and int c; can remain uninitialised.
So all in all it is inevitable that when you print c values as characters you will get "weird" results.
As for negative values, char encrypted[100]; is probably signed char so any integer value in the range 128..255 assigned to that, although undefined behaviour, may possibly show up as a negative number because the signed char is promoted back to int when passed as format %d to printf.
I am not sure why wont this work.I am trying to print lines(from input) that are longer than 80 characters.But i dont get correct characters at all.I am not sure what am i doing wrong.Anyone there knows ??
Note: I dont want you to write me the whole new program doing this function (printing lines that are longer than 80).I just wanna know the wrong side of my program.Correction
Note:Last line overwrites the previous ones.
#include <stdio.h>
#define MAXARRAYSIZE 500
char c;
int i = 0;
int j = 0;
int jCopy = 0;
char line[MAXARRAYSIZE];
char linesToPrint[MAXARRAYSIZE][MAXARRAYSIZE];
void emptyArray(char theArray[]);
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char from[], int toIndex, int lengthSoFar);
void printArray(char theArray[MAXARRAYSIZE][MAXARRAYSIZE], int lengthSoFarX);
int main(void) {
while ((c = getchar()) != EOF) {
if (i > MAXARRAYSIZE) {
i = 0;
}
if (j > MAXARRAYSIZE) {
j = 0;
}
if (c != '\n') {
line[i] = c;
i++;
//printf("%d",i);
} else {
printf("\n j:%d \n i:%d", j, i);
j++;
jCopy = j;
if (i >= 10) {
InsertArrayIntoArray(linesToPrint, line, j, i);
//printArray(linesToPrint, j, i);
}
emptyArray(line);
i = 0;
}
}
printArray(linesToPrint, jCopy);
}
void emptyArray(char theArray[]) {
int i;
for (i = 0; i < sizeof(theArray) / sizeof(theArray[0]); i++) {
theArray[i] = 0;
}
}
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char which[], int toSize, int whichSize) {
int i, j;
//printf("\n To size: %d \t Which Size: %d",toSize,whichSize);
for (i = 0; i < toSize; i++) {
for (j = 0; j < whichSize; j++) {
to[i][j] = which[j];
}
}
}
void printArray(char theArray[MAXARRAYSIZE][MAXARRAYSIZE], int lengthSoFarX) {
int i, j;
for (i = 0; i < lengthSoFarX; i++) {
printf("\n Line %d :", i + 1);
printf(" %s\n", theArray[i]);
}
}
First of all the sizeof(theArray) cannot be taken because theArray is pointer as Joachim Pileborg pointed out.And the second mistake is in InsertArrayIntoArray function.
It should be like this :
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char which[], int toSize, int whichSize) {
int i, j;
//printf("\n To size: %d \t Which Size: %d", toSize, whichSize);
for (j = 0; j < whichSize; j++) {
to[toSize][j] = which[j];
}
}