How do i use 2 separate functions "fgets" for writing into 2 separate variables?

StackOverflow https://stackoverflow.com/questions/21297845

  •  01-10-2022
  •  | 
  •  

Domanda

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)

È stato utile?

Soluzione

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");
        }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top