简体   繁体   English

如何使用2个单独的函数“ fgets”写入2个单独的变量?

[英]How do i use 2 separate functions “fgets” for writing into 2 separate variables?

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. 但是,我只能写变量“ text”,而不能写变量“ key”,并且文本显示方式错误。 How do I fix this? 我该如何解决? (Sorry for bad English) (对不起,英语不好)

fgets writes into the string that's its first argument. fgets将字符串写入它的第一个参数。 Since you were using the same string, the second fgets was overwriting the string from the first one. 由于您使用的是相同的字符串,因此第二个fgets覆盖第一个fgets的字符串。 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");
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM