Question

I've got a code:

 char *text, *key;
 char str[200];
 fputs("Please, enter the text, you want to encrypt:", stdout);
 printf("\n");
 if((text=fgets(str, sizeof(str),stdin))!=NULL)
 {
     printf("Text to encrypt:\n""");
     fputs(text, stdout);
     printf("""\n");
 }


 fputs("Please, enter the key:", stdout);
 printf("\n");
 if((key=fgets(str, sizeof(str),stdin))!=NULL)
 {
     printf("Key:\n""");
     fputs(key, stdout);
     printf("""\n");
 }

I made it that way, because I wanted to write into variable "text" at first, and then, after succesful writing, write into another variable. However, instead I can only write variable "text", but not variable "key", and text is shown wrong way. How do I fix this? (Sorry for bad English)

Was it helpful?

Solution

fgets writes into the string that's its first argument. Since you were using the same string, the second fgets was overwriting the string from the first one. You need two strings.

#include <stdio.h>

int main() {
    char text[200], key[200];
    fputs("Please, enter the text, you want to encrypt:", stdout);
    printf("\n");
    if(fgets(text, sizeof(text),stdin)!=NULL)
        {
            printf("Text to encrypt:\n""");
            fputs(text, stdout);
            printf("""\n");
        }


    fputs("Please, enter the key:", stdout);
    printf("\n");
    if(fgets(key, sizeof(key),stdin)!=NULL)
        {
            printf("Key:\n""");
            fputs(key, stdout);
            printf("""\n");
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top