Question

int i,j,k;
char key[5], input[5], word[7], output[7];

printf("Enter key:\n");
fgets(input, 5, stdin);

printf("Enter word:\n");
fgets(word, 7, stdin);
                                          //I am trying to store two
for (i = 0; i<7; i++) {                   //user-inputted arrays and then
    for (j = 0; j<5; j++) {               //do stuff with them. Fails before
        if (word[i] == key[j]) {          //I even get to the for loop.
            output[i] = input[j];
        }
    }
}

Okay so basically this is the main portion of a program which is supposed to take in two arrays, a secret "key" and a word, composed of 5 and 7 characters respectively, and then by comparing the user-inputted key with a static, hidden key, spit out a NEW translated word which consists of different characters imposed by the user-inputted "key."

Anyways, the function is more-or-less not important because I can't even get my program off the ground! I am new to the fgets() function and am more or less poking around in the dark. Could anyone point me in the right direction?

Thanks.

Was it helpful?

Solution

The reason why fgets is only reading partial input is because the buffer too small. You need to increase the buffer size. Below is working code And what is the content of input[] array?

void main()
{
    int i,j,k,n;
    char key[64], input[64], word[64], output[64];

    printf("Enter key:");
    fgets(input, sizeof(key), stdin);

    input[strlen(input)-1] = '\0';

    printf("Enter word:");
    fgets(word, sizeof(word), stdin);

     word[strlen(word)-1] = '\0';
                                              //I am trying to store two
    for (i = 0; i<7; i++) {                   //user-inputted arrays and then
        for (j = 0; j<5; j++) {               //do stuff with them. Fails before
            if (word[i] == key[j]) {          //I even get to the for loop.
                output[i] = input[j];
            }
        }
    }   

    printf("%s\n",output);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top