Problems reading a file and then writing it in another file - c

So basically this is the code i have to read one file and then encrypt it to another one. The problem i have is that doesn't write anything in the file. Im posting just part of the code because all the code is a big block of code. I thinks its a buffer problem because it doesn't enter in the second while.
char new_array[ROWS+1][COLUMNS+1];
char frase_encriptada[160];
char frase_desencriptada[80];
void xifrar_frase(char frase[80],char matriu_x[7][7], char frase_encriptada[160]){
int i=0;
int j,k,q=0;
while(frase[i] != '\n' && frase[i] !='\0'){
for(j =1;j<=ROWS;j++){
for(k=1;k<=COLUMNS;k++){
if(frase[i] == matriu_x[j][k]){
frase_encriptada[q] = matriu_x[j][0];
q++;
frase_encriptada[q] = matriu_x[0][k];
q++;
}
}
}
i++;
}
printf("\n");
}
void xifrarArxiu(char matriu_x[7][7],char frase[80],char frase_encriptada[160])
{
FILE*fit1;
FILE*fit2;
int i;
fit1 =fopen("txtXifrat.txt","w");
fit2 = fopen("txtDesxifrat.txt","r");
if(fit1 == NULL || fit2 == NULL)
{
printf("Error al obrir un fitxer");
}
else
{
while(fgets(frase,80,fit2)!=NULL)
{
fflush(stdin);
xifrar_frase(frase,new_array,frase_encriptada);
i=0;
while(frase_encriptada[i] !='\0')
{
fprintf(fit1,"%c", frase_encriptada[i]);
i++;
}
}
feof(fit1);
fclose(fit1);
fclose(fit2);
}
}
int main(void) {
int option;
char frase[80];
char array[ROWS][COLUMNS] = {
{'A', 'B', 'C', 'D', 'E', 'F'},
{'G', 'H', 'I', 'J', 'K', 'L'},
{'M', 'N', 'O', 'P', 'Q', 'R'},
{'S', 'T', 'U', 'V', 'W', 'X'},
{'Y', 'Z', ' ', '1', '2', '3'},
{'4', '5', '6', '7', '8', '9'},
};
do
{
MenuOpcions(option);
scanf("%d",&option);
fflush(stdin);
switch (option)
{
case 3:
xifrarArxiu(new_array,frase,frase_encriptada);
break;
case 0:
printf("Sortint del programa \n");
printf("\n");
break;
default:
printf("No hi ha aquesta opcio \n");
printf("\n");
}
}while(option !=0);
return 0;
}

Related

How to use various calculations for various inputs

I am writing a program that will let the user enter various types of information to calculate the expenses for a vacation trip.
I am given the costs of three different forms of transportation, as well as four source cities and four destination cities.
The three forms of travel are air, train and bus, while the source cities are Baltimore, Chattanooga, Nashville, and Pasadena. The destination cities are Denver, Madison, Clarksville, and Knoxville.
I need to be able to calculate the cost to travel between each source and each destination city depending on what the user enters (form of travel, and each city).
Now, my first guess was to write a very very long if/else if statement for each condition. I tried it and it doesn't seem to work either because it is so long or maybe I messed up somewhere.
if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'D', 'd')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'M', 'm')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'K', 'k')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'C', 'c')
transportation_price = 2500;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'D', 'd')
transportation_price = 2500;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'M', 'm')
transportation_price = 2000;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'K', 'k')
transportation_price = 2500;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'C', 'c')
transportation_price = 800;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'D', 'd')
transportation_price = 2000;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'M', 'm')
transportation_price = 1000;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'K', 'k')
transportation_price = 2000;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'C', 'c')
transportation_price = 2000;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'D', 'd')
transportation_price = 2500;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'M', 'm')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'K', 'k')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'C', 'c')
transportation_price = 6000;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'D', 'd')
transportation_price = 500;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'M', 'm')
transportation_price = 2300;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'K', 'k')
transportation_price = 1600;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'C', 'c')
transportation_price = 2000;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'D', 'd')
transportation_price = 600;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'M', 'm')
transportation_price = 1300;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'K', 'k')
transportation_price = 1400;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'C', 'c')
transportation_price = 1700;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'D', 'd')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'M', 'm')
transportation_price = 2500;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'K', 'k')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'C', 'c')
transportation_price = 4500;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'D', 'd')
transportation_price = 1500;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'M', 'm')
transportation_price = 900;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'K', 'k')
transportation_price = 1500;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'C', 'c')
transportation_price = 1700;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'D', 'd')
transportation_price = 1400;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'M', 'm')
transportation_price = 700;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'K', 'k')
transportation_price = 1000;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'C', 'c')
transportation_price = 1300;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'D', 'd')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'M', 'm')
transportation_price = 4500;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'K', 'k')
transportation_price = 3000;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'C', 'c')
transportation_price = 4500;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'D', 'd')
transportation_price = 2000;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'M', 'm')
transportation_price = 1900;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'K', 'k')
transportation_price = 1200;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'C', 'c')
transportation_price = 1700;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'D', 'd')
transportation_price = 1400;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'M', 'm')
transportation_price = 1300;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'K', 'k')
transportation_price = 800;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'C', 'c');
transportation_price = 1300;
I use chars to symbolize each city and form of transportation. This if/else if statement does not work, as in my output all it gives me is a value of $1300 despite what the user enters.
Is there any way I can shorten this down? Or if I messed up somewhere can someone point it out for me?
Any help is appreciated!
At least this problem: Follow code does not compare transportation_type to 'A' and
transportation_type to 'a'. 1
transportation_type == 'A', 'a' // bad
Instead fold the case.
// transportation_type == 'A', 'a'
toupper((unsigned char)transportation_type) == 'A'
Same for others.
Suggest a one time change before the if().
#include <ctype.h>
transportation_type = toupper((unsigned char) transportation_type);
src_city = toupper((unsigned char) src_city);
dest_city = toupper((unsigned char) dest_city);
// if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'D', 'd')
if(transportation_type == 'A' && src_city == 'B' && dest_city == 'D')
1 transportation_type == 'A', 'a' uses the comma operator. The result is 'a'. The result of the compare is lost.
Comma operator with && further complicates things. IAC, , is not needed here.
As mentioned previously, use only uppercase selections or convert the selections to the same case. Additionally, you can store the trip combinations in an array to make the code the cleaner.
#include <stdio.h>
#include <math.h>
int main(){
char transportation_type = 'A';
char src_city = 'B';
char dest_city = 'K';
int transportation_price = 0;
if(transportation_type == 'A' && src_city == 'B' && dest_city == 'D')
transportation_price = 5000;
else if(transportation_type == 'A' && src_city == 'B' && dest_city == 'M')
transportation_price = 4000;
else if(transportation_type == 'A' && src_city == 'B' && dest_city == 'K')
transportation_price = 5000;
printf("%i\n",transportation_price);
// better way, store trip combinations in array
char trips[4][3] = {
{'A','B','D'},
{'A','B','M'},
{'A','B','K'},
{'A','B','C'}
};
int cost[4] = {
5000,4000,5000,2500
};
for (int t=0; t<3; t++) {
if(transportation_type == trips[t][0] && src_city == trips[t][1] && dest_city == trips[t][2]) {
transportation_price = cost[t];
break;
}
}
printf("%i\n",transportation_price);
return transportation_price;
}
Output
5000
5000

Incurring in segmentation fault problems with doubly linked lists in C

I'm trying to insert nodes at the front of a doubly linked list using a function, but I get a segmentation fault error and just can't understand what the problem is. For the typedefing of the pointers I actually know I shouldn't do that, but my teacher asked me to typedef them, for who knows what reason.
Here is the code:
void insertInList(lista_char *pl){
char charSel[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e'};
lista_char new_node = makesNode();
new_node->info = charSel[rand()%10];
new_node->next = *pl;
new_node->prev = NULL;
if(*pl != NULL)
(*pl)->prev = new_node;
*pl = new_node;
}
I think, a pointer with a double star will work:
#include <stdio.h>
#include <stdlib.h>
typedef struct lista_char {
char info;
struct lista_char *next;
struct lista_char *prev;
} lista_char;
lista_char *makesNode()
{
lista_char *node = malloc(sizeof(lista_char));
return (node);
}
void insertInList(lista_char **pl)
{
char charSel[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e'};
lista_char *new_node = makesNode();
new_node->info = charSel[rand() % 10];
new_node->next = *pl;
new_node->prev = NULL;
printf("%c\n", new_node->info);
if (*pl != NULL)
(*pl)->prev = new_node;
*pl = new_node;
}
int main()
{
lista_char *temp;
lista_char *head = NULL;
for (int i = 0; i < 10; i++) {
insertInList(&head);
}
temp = head;
while (temp->next) {
if (temp->prev == NULL) {
printf("prev: %c this: %c next: %c\n", '-', temp->info, (temp->next)->info);
}
else {
printf("prev: %c this: %c next: %c\n", (temp->prev)->info, temp->info, (temp->next)->info);
}
temp = temp->next;
}
printf("prev: %c this: %c next: %c\n", (temp->prev)->info, temp->info, '-');
// free memory
temp = head;
while (temp->next) {
temp = temp->next;
free(temp->prev);
}
free(temp);
return 0;
}

How do I store input in an array and then recall it later?

I have created a morse code input device using the following :
*Arduino Uno
*Grove Base sheild
*Grove button
*Grove light sensor
*LCD RGB Backlight
I have it so that a word is displayed on the LCD (in this case 'yellow'). That word then has to be input as morse code via the button.
As it is input, the letters are translated from Morse code to English and displayed as letters on the screen.
(The light sensor is used to reset the LCD).
My question is this ... How would I go about having the answer being input as morse code stored and then checked for correctness? So if my daughter inputs "Yellop" it would display a message saying "Incorrect". She would reset and try again.
I am very very new to all of this and would love some help getting this up and running.
Now, I am assuming I would somehow have to have each letter input stored in some sort of array and then checked for correctness. However, I have no idea how to do that.
Here is my code ...
#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;
#define DOT false
#define DASH true
#define MAX_CHAR_LENGTH 6
#define BUTTON A0
#define LIGHTSENSOR A1
#define pinLED 6
#define PULSE_THRESHOLD 400
#define LETTER_SEPARATION 600
#define WORD_SEPARATION 8000
const struct MorseTree *tree = NULL;
const int colorR = 0;
const int colorG = 0;
const int colorB = 100;
int value;
int button = -1;
int pulseThreshold = 0;
int letterSeparation = 0;
int wordSeparation = 0;
void initMorse(int lbutton, int lpulseThreshold, int lletterSeparation, int
lwordSeparation)
{
tree = generateMorseTree();
button = lbutton;
pulseThreshold = lpulseThreshold;
letterSeparation = lletterSeparation;
wordSeparation = lwordSeparation;
}
struct MorseTree
{
// '-' unless this is a leaf node
char character;
struct MorseTree *dotChild;
struct MorseTree *dashChild;
};
struct MorseData
{
char character;
bool code[MAX_CHAR_LENGTH];
byte codeLength;
};
void initMorseTree(struct MorseTree *tree)
{
tree -> character = '-';
tree -> dotChild = NULL;
tree -> dashChild = NULL;
}
struct MorseTree *newMorseTree()
{
struct MorseTree *tree = (struct MorseTree *) malloc(sizeof(struct
MorseTree));
initMorseTree(tree);
return tree;
}
void addTreeMember(struct MorseTree *tree, struct MorseData &data)
{
struct MorseTree *current = tree;
for (byte i = 0; i < data.codeLength; i++)
{
boolean currentSymbol = data.code[i];
if (currentSymbol == DOT)
{
if (current -> dotChild == NULL)
current -> dotChild = newMorseTree();
current = current -> dotChild;
}
else
{
if (current -> dashChild == NULL)
current -> dashChild = newMorseTree();
current = current -> dashChild;
}
}
// now current must be a leaf node
current -> character = data.character;
}
void addTreeMembers(struct MorseTree *tree, struct MorseData data[],
byte dataLength)
{
for (byte i = 0; i < dataLength; i++)
addTreeMember(tree, data[i]);
}
void addAlphabet(struct MorseTree *tree)
{
struct MorseData data[] = {
{'A', {DOT, DASH}, 2},
{'B', {DASH, DOT, DOT, DOT}, 4},
{'C', {DASH, DOT, DASH, DOT}, 4},
{'D', {DASH, DOT, DOT}, 3},
{'E', {DOT}, 1},
{'F', {DOT, DOT, DASH, DOT}, 4},
{'G', {DASH, DASH, DOT}, 3},
{'H', {DOT, DOT, DOT, DOT}, 4},
{'I', {DOT, DOT}, 2},
{'J', {DOT, DASH, DASH, DASH}, 4},
{'K', {DASH, DOT, DASH}, 3},
{'L', {DOT, DASH, DOT, DOT}, 4},
{'M', {DASH, DASH}, 2},
{'N', {DASH, DOT}, 2},
{'O', {DASH, DASH, DASH}, 3},
{'P', {DOT, DASH, DASH, DOT}, 4},
{'Q', {DASH, DASH, DOT, DASH}, 4},
{'R', {DOT, DASH, DOT}, 3},
{'S', {DOT, DOT, DOT}, 3},
{'T', {DASH}, 1},
{'U', {DOT, DOT, DASH}, 3},
{'V', {DOT, DOT, DOT, DASH}, 4},
{'W', {DOT, DASH, DASH}, 3},
{'X', {DASH, DOT, DOT, DASH}, 4},
{'Y', {DASH, DOT, DASH, DASH}, 4},
{'Z', {DASH, DASH, DOT, DOT}, 4},
};
addTreeMembers(tree, data, 26);
}
void addNumbers(struct MorseTree *tree)
{
struct MorseData data[] = {
{'1', {DOT, DASH, DASH, DASH, DASH}, 5},
{'2', {DOT, DOT, DASH, DASH, DASH}, 5},
{'3', {DOT, DOT, DOT, DASH, DASH}, 5},
{'4', {DOT, DOT, DOT, DOT, DASH}, 5},
{'5', {DOT, DOT, DOT, DOT, DOT}, 5},
{'6', {DASH, DOT, DOT, DOT, DOT}, 5},
{'7', {DASH, DASH, DOT, DOT, DOT}, 5},
{'8', {DASH, DASH, DASH, DOT, DOT}, 5},
{'9', {DASH, DASH, DASH, DASH, DOT}, 5},
{'0', {DASH, DASH, DASH, DASH, DASH}, 5},
};
addTreeMembers(tree, data, 10);
}
void addPunctuation(struct MorseTree *tree)
{
struct MorseData data[] = {
{'.', {DOT, DASH, DOT, DASH, DOT, DASH}, 6},
{',', {DASH, DASH, DOT, DOT, DASH, DASH}, 6},
{'?', {DOT, DOT, DASH, DASH, DOT, DOT}, 6},
};
addTreeMembers(tree, data, 3);
}
struct MorseTree *generateMorseTree()
{
struct MorseTree *tree = newMorseTree();
initMorseTree(tree);
addAlphabet(tree);
addNumbers(tree);
addPunctuation(tree);
return tree;
}
void waitFor(int pin, int state)
{
do
{
// spin until the pin reads the given state
while (digitalRead(pin) != state) { }
// delay, to verify the reading
delay(5);
// continue if the reading has changed
} while (digitalRead(pin) != state);
}
boolean getNextSymbol()
{
waitFor(button, HIGH);
unsigned long start = millis();
waitFor(button, LOW);
unsigned long end = millis();
unsigned long pulseLength = end - start;
// Serial.println(pulseLength);
if (pulseLength > pulseThreshold)
return DASH;
else
return DOT;
}
boolean shouldTimeOut()
{
unsigned long start = millis();
while (digitalRead(BUTTON) == LOW)
{
if (millis() - start > letterSeparation)
return true;
}
return false;
}
boolean shouldBeSpace()
{
unsigned long start = millis();
while (digitalRead(BUTTON) == LOW)
{
if (millis() - start > wordSeparation)
return true;
}
return false;
}
char getNextChar()
{
static boolean lastCharWasSpace = false;
const struct MorseTree *current = tree;
byte symbolCount = 0;
if (!lastCharWasSpace && shouldBeSpace())
{
lastCharWasSpace = true;
return ' ';
}
lastCharWasSpace = false;
while (true)
{
symbolCount++;
boolean currentSymbol = getNextSymbol();
// Serial.println(currentSymbol == DOT ? "DOT" : "DASH");
if (currentSymbol == DOT)
current = current -> dotChild;
else
current = current -> dashChild;
if (current == NULL)
return '-';
if (shouldTimeOut() || symbolCount >= MAX_CHAR_LENGTH)
return current -> character;
}
// should never get here
return '!';
}
void setup()
{
pinMode(BUTTON, INPUT);
pinMode(LIGHTSENSOR, INPUT);
value = analogRead(LIGHTSENSOR);
initMorse(BUTTON, PULSE_THRESHOLD, LETTER_SEPARATION, WORD_SEPARATION);
Serial.begin(9600);
while(! Serial);
lcd.begin(16, 2);
lcd.setRGB(colorR, colorG, colorB);
lcd.print("Input 'yellow'");
}
void loop()
{
Serial.println(value);
value = analogRead(LIGHTSENSOR);
if(value<40)
{
lcd.clear();
}
static boolean firstLoop = true; //skips the first space between words.
char c = getNextChar();
if (firstLoop)
{
firstLoop = false;
if (c == ' ')
return;
}
lcd.print(c);
}
Any help or advice would be greatly appreciated.
(I deleted my last question and reposted as it was very badly worded. Hopefully this one is better!)

Function and loop trouble in C

This program is expecting the user to input a 7-digit number (except 1 and 0), and any digit has a corresponding set of letters
(2=ABC, 3=DEF, 4=GHI, 5=JKL, 6=MNO, 7=PRS, 8=TUV, 9=XYZ, as found on phones in the USA). Finally, it should output all 2187 possible sequences of letters.
ex: input 2345678
output should be ADGJMPT ADGJMPU ADGJMPV ADGJMRT ADGJMRU ADGJMRV ADGJMST..........CFILOSV
but my output always is AAAAAAA AAAAAAB AAAAAAC..........CCCCCCC
(I also have trouble in checking number. I first set a loop and array, if (che[1] != 1 && che[0] != 1) break; but sometimes it doesn't break.)
Can you explain what's wrong?
#include<stdio.h>
int main(){
int che[50] = { 0 };
int a, b, c, d, e, f, g, i, r, q, number, check;
char word2[7];
char word1[8][3] = {
{ 'A', 'B', 'C' },
{ 'D', 'E', 'F' },
{ 'G', 'H', 'I' },
{ 'J', 'K', 'L' },
{ 'M', 'N', 'O' },
{ 'P', 'R', 'S' },
{ 'T', 'U', 'V' },
{ 'W', 'X', 'Y' } };
while (1)
{
printf("Enter seven digit(except 0 and 1):");
scanf("%d", &number);
check = number;
for (; number != 0; number /= 10)
{
q = number % 10;
che[q] = 1;
}
if (che[1] != 1 && che[0] != 1) break;
}
number = check;
for (i = 6; number == 0; i--)
{
r = number % 10;
if (r == 2){ word2[i] = 0; }
if (r == 3){ word2[i] = 1; }
if (r == 4){ word2[i] = 2; }
if (r == 5){ word2[i] = 3; }
if (r == 6){ word2[i] = 4; }
if (r == 7){ word2[i] = 5; }
if (r == 8){ word2[i] = 6; }
if (r == 9){ word2[i] = 7; }
number /= 10;
}
for (a = 0; a < 3; a++){
for (b = 0; b < 3; b++){
for (c = 0; c < 3; c++){
for (d = 0; d < 3; d++){
for (e = 0; e < 3; e++){
for (f = 0; f < 3; f++){
for (g = 0; g < 3; g++){
printf("%c%c%c%c%c%c%c ",word1[word2[0]][a], word1[word2[1]][b], word1[word2[2]][c], word1[word2[3]][d], word1[word2[4]][e], word1[word2[5]][f], word1[word2[6]][g]);
}
}
}
}
}
}
}
return 0;
}
Main problem is here:
for (i = 6; number == 0; i--)
The loop condition is the opposite of the one it should be. You want to keep iterating on the number until you reach 0 (by successively dividing it by 10).
It should be
for (i = 6; number != 0; i--)
or
for (i = 6; i >= 0; i--)
In addition mind that
if (r == 2){ word2[i] = 0; }
if (r == 3){ word2[i] = 1; }
if (r == 4){ word2[i] = 2; }
if (r == 5){ word2[i] = 3; }
if (r == 6){ word2[i] = 4; }
if (r == 7){ word2[i] = 5; }
if (r == 8){ word2[i] = 6; }
if (r == 9){ word2[i] = 7; }
is equivalent to
if (r >= 2 && r <= 9)
word2[i] = r - 2;
I think this works as you expected:
For some convenience in debugging, I changed some IO format:
Input separated number 2-9 divided by space and end with -1.
The input sequence can be of any length, just end with -1.
For example, input:2 3 4 2 -1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char word1[8][3] = {
{ 'A', 'B', 'C' },
{ 'D', 'E', 'F' },
{ 'G', 'H', 'I' },
{ 'J', 'K', 'L' },
{ 'M', 'N', 'O' },
{ 'P', 'R', 'S' },
{ 'T', 'U', 'V' },
{ 'W', 'X', 'Y' } };
void translate(char * headStr,int * pattern,int pos_to_do)
{
if(pattern[pos_to_do]<0)
{
printf("%s\n",headStr);
return;
}
char str[3][20];
int i;
for(i=0;i<3;i++)
{
strcpy(str[i],headStr);
char str_this[2];
str_this[0]=word1[ pattern[pos_to_do] ][i];
str_this[1]='\0';
strcat(str[i],str_this);
translate(str[i],pattern,pos_to_do+1);
}
return;
}
int main(){
int che[20];
int number, check,len;
while (1)
{
printf("Enter digits(except 0 and 1):");
len=0;
scanf(" %d", &number);
while(number>=2)
{
che[len]=number-2;
len++;
scanf("%d", &number);
}
che[len]=-1;
char str_start[]="";
translate(str_start,che,0);
}
return 0;
}
Test output:
Enter digits(except 0 and 1):2 3 4 -1
ADG
ADH
ADI
AEG
AEH
AEI
AFG
AFH
AFI
BDG
BDH
BDI
BEG
BEH
BEI
BFG
BFH
BFI
CDG
CDH
CDI
CEG
CEH
CEI
CFG
CFH
CFI
Enter digits(except 0 and 1):

Certain statements printing twice

In a hangman program I'm writing, words with two of the same letter, such as "eel" or "bee," upon the user entering "e" the first time and then trying to enter "e" for the second prompt, will display "You've already guessed this letter" twice. How can I fix this?
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
int main(){
char w[13][3] = {
{ 'c', 'a', 't' }, //0
{ 'd', 'o', 'g' }, //1
{ 'r', 'a', 't' }, //2
{ 'e', 'e', 'l' }, //3
{ 'c', 'o', 'w' }, //4
{ 'o', 'w', 'l' }, //5
{ 'e', 'm', 'u' }, //6
{ 'b', 'a', 't' }, //7
{ 'e', 'l', 'k' }, //8
{ 'p', 'i', 'g' }, //9
{ 'b', 'e', 'e' }, //10
{ 'h', 'e', 'n' }, //11
{ 'f', 'o', 'x' }, //12
};
char u,
newline,
dis[16];
int random,
guesses = 3,
finish = 0;
_Bool successfulGuess = false;
srand(time(NULL));
random = rand() % 13;
printf("Animal %d\n", random); //check random number
printf("---------\n\n");
printf("Enter a letter: ");
u = getchar();
newline = getchar();
for (int i = 0; i < 3; i++){
if (w[random][i] == u){
successfulGuess = true;
dis[i] = u;
}
else {
dis[i] = '_';
}
}
for (int j = 0; j < 3; j++){
dis[j] = dis[j];
}
printf("\n");
for (int i = 0; i < 3; i++){
printf("%c", dis[i]);
}
if (successfulGuess == false){
--guesses;
}
printf("\n\nGuesses left: %d", guesses);
printf("\n\n");
while (guesses > 0){
finish = 0;
successfulGuess = false;
printf("Enter a letter: ");
u = getchar();
newline = getchar();
for (int i = 0; i < 3; i++){
if (u == dis[i]){
successfulGuess = true;
printf("\nYou already guessed this letter.\n");
printf("\ninput = dis[i]\nGuesses left: %d\n\n", guesses);
}
else if (w[random][i] == u){
successfulGuess = true;
dis[i] = u;
printf("\ninput = array char\nGuesses left: %d\n\n", guesses);
}
}
for (int i = 0; i < 3; i++){
printf("%c", dis[i]);
}
if (successfulGuess == false){
guesses--;
printf("\n\nbool statement\nGuesses left: %d\n\n", guesses);
}
if (guesses == 0){
printf("Sorry, you've run out of guesses.");
}
for (int i = 0; i < 3; i++) {
if (dis[i] != '_') {
finish++;
}
if (finish == 3){
printf("\n\nYou guessed the word!");
guesses = 0;
}
else{
continue;
}
}
printf("\n\n");
}
system("pause");
}
You are looping i three times even if you have already shown the message. I think it should break ather the message:
for (int i = 0; i < 3; i++){
if (u == dis[i]){
successfulGuess = true;
printf("\nYou already guessed this letter.\n");
printf("\ninput = dis[i]\nGuesses left: %d\n\n", guesses);
/* BREAK HERE */
break;
}

Resources