Task: Converts Ohm's from 1 kOhm to 1000 Ohm etc. and find max and min values.
Example:
1 kOhm
2 Ohm
And after convert to
1000 Ohm
2 Ohm
But after input get only
1 kOhm
Ohm
Input must be with spaces. Program drops 1 char from every new line after first. I try using wscanf and other thinks but it isn't workig for me.
P.S. I must use wchar_t
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
int pow(int base, int exp) {
if (exp < 0)
return -1;
int result = 1;
while (exp) {
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;
}
return result;
}
int transformSize(wchar_t name) {
if (name == L'h') {
return 2;
} else if (name == L'k') {
return 3;
} else if (name == L'M') {
return 6;
} else if (name == L'G') {
return 9;
} else if (name == L'T') {
return 12;
} else if (name == L'P') {
return 15;
} else if (name == L'E') {
return 18;
} else if (name == L'Z') {
return 21;
} else if (name == L'Y') {
return 24;
}
return 0;
}
int main() {
unsigned int *numbers;
unsigned int min = 0;
unsigned int max = 0;
int n = 0;
wchar_t **array;
setlocale(LC_ALL, "");
wprintf(L"Enter n: ");
wscanf(L"%d", &n);
array = malloc(n * sizeof(wchar_t *));
numbers = malloc(n * sizeof(unsigned int *));
wprintf(L"Enter n-elements: \n");
for (int i = 0; i < n; i++) {
wchar_t temp;
array[i] = malloc(256 * sizeof(wchar_t));
wscanf(L"%c", &temp);
fgetws(array[i], 2560, stdin);
}
wprintf(L"\n\nStart array: [");
for (int i = 0; i < n; i++) {
wprintf(L" ");
wprintf(L"%ls", array[i]);
wprintf(L" ");
}
wprintf(L"]\n\n");
for (int i = 0; i < n; i++) {
int spaceIndex = 0;
for (int j = 0; j < wcslen(array[i]); j++) {
if (array[i][j] != ' ') {
spaceIndex++;
} else {
break;
}
}
wchar_t *new = malloc(sizeof(wchar_t) * spaceIndex + 1);
wcsncpy(new, array[i], spaceIndex);
new[n] = '\0';
numbers[i] = wcstol(new, (wchar_t **)NULL, 10) *
(pow(10.0, (double)transformSize(array[i][spaceIndex + 1])));
if (i == 0) {
min = numbers[i];
max = numbers[i];
}
if (numbers[i] >= max) {
max = numbers[i];
}
if (numbers[i] <= min) {
min = numbers[i];
}
free(new);
}
wprintf(L"Converted array: [");
for (int i = 0; i < n; i++) {
wprintf(L" %ld Ohm ", numbers[i]);
}
wprintf(L"]\n\n");
wprintf(L"Max element: %ld Ohm\n", max);
wprintf(L"Min element: %ld Ohm\n", min);
for (int i = 0; i < n; i++) {
free(array[i]);
}
free(array);
return 0;
}
Example of current program input/output:
Enter n: 3
Enter n-elements:
12 kOhm
3 kOhm
1 Ohm
// Must be 12 kOhm, 3 kOhm, 1 Om
Start array: [ 12 kOhm
kOhm
Ohm
]
// Must be 12000 Ohm, 3000 Ohm, 1 Ohm
Converted array: [ 12000 Ohm 0 Ohm 0 Ohm ]
Max element: 12000 Ohm
Min element: 0 Ohm
Mixing fgetsw and wscanf is a bad idea.
The problem is here:
...
for (int i = 0; i < n; i++) {
wchar_t temp;
array[i] = malloc(256 * sizeof(wchar_t));
wscanf(L"%c", &temp);
fgetws(array[i], 2560, stdin);
}
...
You are using wscanf(L"%c", &temp); to absorb the line feed that is left over from wscanf. You should do this only once after the wscanflike this:
...
wchar_t temp;
wscanf(L"%c", &temp);
for (int i = 0; i < n; i++) {
array[i] = malloc(256 * sizeof(wchar_t));
fgetws(array[i], 2560, stdin);
}
...
But the best would be not to mix wscanf and fgetsw in first place.
I suppose you use Visual Studio. If yes, learn how to use the debugger, it's very easy to use and very powerful. If no, learn how to use your debugger anyway.
But further in your program there may be other problems unrelated to your question, I didn't check.
Related
I'm doing the day 8 of the 30 days of code in HackerRank and I am having a problem with strcmp.
The code asks the user for names of people and their numbers, then asks for other names, if a name wasn't entered before, then it outputs Not found, but if it was then it outputs the name and his number. But for some reason, the output only works in the last loop of the for statement.
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
scanf("%i", &n);
} while (n < 1 || n > 100000);
int i = 0;
phonebook people[n];
for (i = 0; i < n; i++) {
scanf("%s %i", people[i].name, &people[i].number);
}
char othernames[n][100];
for (i = 0; i < n; i++) {
scanf("%s", othernames[i]);
}
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
} else {
printf("Not found\n");
}
}
return 0;
}
You didn't find the othernames from the beginning to end to compare peopleevery time, so you need to replace
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
}
else {
printf("Not found\n");
}
}
to
bool found = false;
for (i = 0; i < n; i++) {
for ( j = 0 ; j < n ; j++ ) {
if (strcmp(othernames[j], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
found = true;
}
}
}
if ( found == false ) printf("Not found\n");
The problem is othernames should just be an array of char, not a matrix. And for each othername entered, you must scan whole phonebook to find it or display Not found. As coded, you only test if the i-th othername typed happens to correspond to the i-th entry in the phone book.
Here is a modified version:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
if (scanf("%i", &n) != 1)
return 1;
} while (n < 1 || n > 100000);
phonebook people[n];
for (int i = 0; i < n; i++) {
if (scanf("%99s %i", people[i].name, &people[i].number) != 2)
return 1;
}
for (int i = 0; i < n; i++) {
char othername[100];
if (scanf("%99s", othername) != 1)
break;
int j;
for (j = 0; j < n; j++) {
if (strcmp(othername, people[j].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
break;
}
}
if (j == n) {
printf("Not found\n");
}
}
return 0;
}
Note that it is probably not a good idea to store phone numbers as int values. Better use a char array so an initial 0 is significant and to store longer numbers.
I'm trying to make a board 5x5 and in the middle of this board (that's mean i > 0 and i < 4 ) i want to put a piece in this sub board in randomic way, only 7 theme(if the random number are the same than previous the print have to be the sum of all the pieces above each others).I'm using the dynamic stack for training purpose. I can drew the board exact like i want but i couldn't solve till now de segmentation fault
(EDIT: I already responded this questions with details.)
here is all code;
#include<stdlib.h>
#include<math.h>
#include <stdlib.h>
#include<time.h>
#include <stdbool.h>
typedef struct peca
{
int andares;
int parque;
int teto;
struct peca *prox;
} peca;
typedef struct jogador
{
int andares;
int parque;
int teto;
} jogador;
int aleatorio[101];
main ()
{
jogador norte, sul, leste, oeste;
peca *tabuleiro[5][5];
int por_parque = 0;
srand(time(NULL));
for (int i = 0; i < 101; i++)
{
aleatorio[i] = rand() % 4;
if(i % 2 == 0 && i == 0)
{
aleatorio[i] = aleatorio[i] + 2;
}
else if (i % 2 != 0 && i == 0)
{
aleatorio[i]++;
}
}
printf (" ");
printf (" Norte\n");
for (int i = 0; i < 5; i++)
{
printf (" ");
printf ("+");
for (int j = 0; j < 5; j++)
{
printf ("----");
if (j % 5 == 0);
{
printf ("+");
}
}
printf ("\n");
if (i == 2)
{
printf (" Oeste ");
printf ("|");
}
else
{
printf (" ");
printf ("|");
}
for (int k = 0; k < 5; k++)
{
if ((k > 0 && k < 4) && (i > 0 && i < 4))
{
bool vazio_ou_n = false;
//===========================================================================================
for (int l = 0; l < 100; l++)
{
if (aleatorio[l] == k && aleatorio[l + 1] == i)
{
por_parque++;
vazio_ou_n = true;
break;
}
}
if (vazio_ou_n && por_parque < 7)
{
//============================================================================================
peca * n = malloc(sizeof(peca));
if (n == NULL)
{
printf("erro");
return 1;
}
n->andares++;
if(tabuleiro[i][k] == NULL)
{
tabuleiro[i][k] = n;
n->prox = NULL;
}
else
{
n -> andares = tabuleiro[i][k] -> andares;
n -> andares++;
n -> prox = tabuleiro[i][k];
tabuleiro[i][k] = n;
}
printf(" %d ", tabuleiro[i][k]->andares);
printf ("|");
vazio_ou_n = false;
continue;
}
else if (vazio_ou_n && por_parque == 7)
{
//=====================================================================
peca * n = malloc(sizeof(peca));
n->parque = 1;
if (tabuleiro[i][k] == NULL)
{
tabuleiro[i][k] = n;
}
else
{
por_parque--;
continue;
}
printf("[ %d]", tabuleiro[i][k]->parque);
printf ("|");
vazio_ou_n = false;
continue;
}
}
for (int l = 0; l < 4; l++)
{
printf ("%c", ' '); //"liga" o desenho do tabuleiro a matriz do jogo
}
if (k % 5 == 0);
{
printf ("|");
}
}
//letras do lado direito do tabuleiro
printf (" %c", i + 97);
if (i == 2)
{
printf (" Leste ");
}
printf ("\n");
}
// ultima linh do tabuleiro
printf (" ");
printf ("+");
for (int j = 0; j < 5; j++)
{
printf ("----");
if (j % 5 == 0);
{
printf ("+");
}
}
//numeros de baixo do tabuleiro
printf ("\n");
printf (" ");
for (int j = 0; j < 5; j++)
{
printf (" %d ", j + 1);
if (j % 5 == 0);
{
printf (" ");
}
}
printf ("\n");
printf (" ");
printf (" Sul\n");
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
peca* tmp = NULL;
peca* fre = tabuleiro[i][j];
while (fre != NULL)
{
tmp = fre -> prox;
free(fre);
fre = tmp;
}
}
}
}
the part that that i have been thinking tha were the bug
if (n == NULL)
{
printf("erro");
return 1;
}
n->andares++;
if(tabuleiro[i][k] == NULL)
{
tabuleiro[i][k] = n;
n->prox = NULL;
}
else
{
n -> andares = tabuleiro[i][k] -> andares;
n -> andares++;
n -> prox = tabuleiro[i][k];
tabuleiro[i][k] = n;
} ```
I'm new programing and i still don't know use debugger very well, so if anyone can help, i'm glad
(i%2==0 && i==0)
You're telling the computer: if it's even and is equal to zero.. . See it?
It was a poor code but I believe now it might help someone. Besides the other errors , I'll show them in the code below. The main problem was the segment fault and the way I was dealing with pointers. And it is the main point that I would like to talk about, because this is what will help whoever find this question and also is the answer to this question.
There are two errors exactly regarding the poiterns dealing. The first one is peca *tabuleiro[5][5]; where is the segment fault. In some "intuitive way" while you are coding you may think the once you typed peca *tabuleiro[5][5]; as int type variables, this will be set to NULL automatically as a pattern behavior.
But it points to a random location in memory when you declare it. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system. It should be peca *tabuleiro[5][5] = {{NULL}}; becouse you need to set them for NULL.
And the second error was that for the almost same reason, once you fix the mistake there are some random huge integers instead of what is expected. And this is happening because once was created the new peace peca * n = malloc(sizeof(peca)); the n->andares point to a space in memory but not overlay the integer there. I fix the code and commented what i replace.
#include<stdlib.h>
#include<math.h>
#include <stdio.h>
/*#include<stdlib.h>*/
#include<time.h>
#include <stdbool.h>
typedef struct peca
{
int andares;
int parque;
int teto;
struct peca *prox;
} peca;
typedef struct jogador
{
int andares;
int parque;
int teto;
} jogador;
int aleatorio[101];
int main ()
{
jogador norte, sul, leste, oeste;
/*peca *tabuleiro[5][5];*/
peca *tabuleiro[5][5] = {{NULL}};
int por_parque = 0;
srand(time(NULL));
for (int i = 0; i < 101; i++)
{
aleatorio[i] = rand() % 4;
/*if(i % 2 == 0 && i == 0)*/
if(i % 2 == 0 || i == 0)
{
aleatorio[i] = aleatorio[i] + 2;
}
/*else if (i % 2 != 0 && i == 0)*/
else if (i % 2 != 0 || i == 0)
{
aleatorio[i]++;
}
}
printf (" ");
printf (" Norte\n");
for (int i = 0; i < 5; i++)
{
printf (" ");
printf ("+");
for (int j = 0; j < 5; j++)
{
printf ("----");
if (j % 5 == 0);
{
printf ("+");
}
}
printf ("\n");
if (i == 2)
{
printf (" Oeste ");
printf ("|");
}
else
{
printf (" ");
printf ("|");
}
for (int k = 0; k < 5; k++)
{
if ((k > 0 && k < 4) && (i > 0 && i < 4))
{
bool vazio_ou_n = false;
//===========================================================================================
/*for (int l = 0; l < 100; l++)*/
for (int l = 0; l < 99; l++)
{
if (aleatorio[l] == k && aleatorio[l + 1] == i)
{
por_parque++;
vazio_ou_n = true;
break;
}
}
if (vazio_ou_n && por_parque < 7)
{
//============================================================================================
peca * n = malloc(sizeof(peca));
if (n == NULL)
{
printf("erro");
return 1;
}
n->andares = 1;
n->teto = 0;
n->parque = 0;
n->prox = NULL;
/*n->andares++;*/
if(tabuleiro[i][k] == NULL)
{
tabuleiro[i][k] = n;
n->prox = NULL;
}
else
{
n -> andares = tabuleiro[i][k] -> andares;
n -> andares++;
n -> prox = tabuleiro[i][k];
tabuleiro[i][k] = n;
}
printf(" %d ", tabuleiro[i][k]->andares);
printf ("|");
vazio_ou_n = false;
continue;
}
else if (vazio_ou_n && por_parque == 7)
{
//=====================================================================
peca * n = malloc(sizeof(peca));
n->parque = 1;
if (tabuleiro[i][k] == NULL)
{
tabuleiro[i][k] = n;
}
else
{
por_parque--;
continue;
}
printf("[ %d]", tabuleiro[i][k]->parque);
printf ("|");
vazio_ou_n = false;
continue;
}
}
for (int l = 0; l < 4; l++)
{
printf ("%c", ' '); //"liga" o desenho do tabuleiro a matriz do jogo
}
if (k % 5 == 0);
{
printf ("|");
}
}
//letras do lado direito do tabuleiro
printf (" %c", i + 97);
if (i == 2)
{
printf (" Leste ");
}
printf ("\n");
}
// ultima linh do tabuleiro
printf (" ");
printf ("+");
for (int j = 0; j < 5; j++)
{
printf ("----");
if (j % 5 == 0);
{
printf ("+");
}
}
//numeros de baixo do tabuleiro
printf ("\n");
printf (" ");
for (int j = 0; j < 5; j++)
{
printf (" %d ", j + 1);
if (j % 5 == 0);
{
printf (" ");
}
}
printf ("\n");
printf (" ");
printf (" Sul\n");
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
peca* tmp = NULL;
peca* fre = tabuleiro[i][j];
while (fre != NULL)
{
tmp = fre -> prox;
free(fre);
fre = tmp;
}
}
}
return 0;
}
I redone this project and proposed a mathematical way to solve the proposed main problem. Hope that it was helpfull.
My program takes 3 lines of input. The first line being whether you want to sort it by odd or even, the second line being how large your array is and the third line being the integers in the array. It works until you use an array larger than 8. I believe it's to do with malloc but I've tried to debug this code for a couple of hours now and I can't fix this issue.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* sort;
int n;
int* ar;
int i;
int test()
{
int temp;
int j = 1;
//printf("%s", sort);
if (strcmp(sort, "odd") == 0) {
for (i = 0; i < n;) {
if (j != n) {
if (ar[i] % 2 != 0) {
if (ar[j] % 2 != 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
if (strcmp(sort, "even") == 0) {
for (i = 0; i < n; i++) {
if (j != n) {
if (ar[i] % 2 == 0) {
if (ar[j] % 2 == 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
}
void main()
{
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
//printf("%s", sort);
printf("Enter the elements of the array \n");
for (i = 0; i < n; i++) {
scanf("%d", &ar[i]);
}
test();
for (i = 0; i < n; i++) {
printf("%d ", ar[i]);
}
// return 0;
}
Code is typically executed in a linear fashion, but you don't seem to be doing that. You're allocating ar using n, but don't have a value for n yet until several lines later...
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
You're also not allocating the size of sort big enough to contain any string longer than 1 character.
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 have a problem thats giving me a huge ache.
This piece of code purpose is to fill up an array with integer values and at the same time defend against strings and etc....but it doesn't defend against duplicates, but tried I got to far as replacing the number with a new number for example
Enter 6 integers
1, 2, 2, 3, 4, 5
my code will let me replace that 2 at position 1 with another number. What I want it to do is not to repeat the same number again, for example please replace 2 at position 1. I dont want the user to enter 2 again... and I want to make it to double check the work the array if any repeating numbers exists thank you.
system("clear");
printf("\nEntering Winning Tickets....\n");
nanosleep((struct timespec[]){{1, 0}}, NULL);
system("clear");
char userInput[256];
char c;
int duplicationArray[6] = {-1, -1, -1, -1, -1, -1};
for (i = 0; i < 6; i++)
{
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
for (i = 0; i < 6 - 1; ++i)
{
min = i;
for (j = i+1; j < 6; ++j)
{
if (winningNumbers[j] < winningNumbers[min])
min = j;
}
temp = winningNumbers[i];
winningNumbers[i] = winningNumbers[min];
winningNumbers[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
if (duplicationCounter > -6)
{
for (i = 0; i < 6; i++)
{
int j, min, temp;
min = i;
for (j = i+1; j < 6; ++j)
{
if (duplicationArray[j] > duplicationArray[min])
min = j;
}
temp = duplicationArray[i];
duplicationArray[i] = duplicationArray[min];
duplicationArray[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (duplicationArray[i] == -1)
{
zeroCounter++;
}
}
int resize = (6 - zeroCounter)+1;
for (i = 0; i <= resize; i++)
{
if (duplicationArray[i] == -1)
{
i++;
}
else if (duplicationArray[i] != -1)
{
system("clear");
printf("\nDuplicated numbers has been dected in your array. ");
printf("\nPlease replace the number %d at postion %d with another number: ", winningNumbers[duplicationArray[i]], duplicationArray[i]);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[duplicationArray[i]], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
}
duplicationCounter = 0;
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
printf("%d, ", duplicationCounter);
}
#include <stdio.h>
#include <stdint.h>
#define DATA_SIZE 6
int main(void){
char userInput[256];
int inputNum, winningNumbers[DATA_SIZE];
uint64_t table = 0;
int i=0;
while(i<DATA_SIZE){
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, sizeof(userInput), stdin);
if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
continue;
uint64_t bit = 1 << inputNum;
if(table & bit)
continue;
table |= bit;
winningNumbers[i++] = inputNum;
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 6
int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
char inputLine[256];
int n;
for(;;){
printf("%s", msg);
fgets(inputLine, sizeof(inputLine), stdin);
if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
fprintf(stderr, "%s", errMsg);
else
return n;
}
}
int inputNumber(void){
return inputNumberWithRangeCheck(
"\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
"Invalid Input.\n",
1,49);
}
int *inputArray(int *array, size_t size){
int i;
for(i=0;i<size;++i){
printf("\nInput for No.%d\n", i+1);
array[i] = inputNumber();
}
return array;
}
int **duplicateCheck(int *array, size_t size){
int **check, count;
int i, j;
check = malloc(size*sizeof(int*));
if(!check){
perror("memory allocate\n");
exit(-1);
}
//There is no need to sort the case of a small amount of data
//(Cost of this loop because about bubble sort)
for(count=i=0;i<size -1;++i){
for(j=i+1;j<size;++j){
if(array[i] == array[j]){
check[count++] = &array[i];
break;
}
}
}
check[count] = NULL;
if(count)
return check;
else {
free(check);
return NULL;
}
}
int main(void){
int winningNumbers[DATA_SIZE];
int **duplication;
int i, j;
inputArray(winningNumbers, DATA_SIZE);
while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
for(i=0;i<DATA_SIZE;++i){
if(duplication[i]){
printf("\nyour input numbers : ");
for(j=0;j<DATA_SIZE;++j)
printf("%d ", winningNumbers[j]);
fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
*duplication[i] = inputNumber();
} else
break;
}
free(duplication);
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}