fgets()如何从stdin读取数据?

3
如果我需要使用 fgets() 两次从键盘读取两个不同的输入,我应该指定两个不同的缓冲区还是重复使用同一个缓冲区?有什么区别吗?
重复使用同一个缓冲区:
   char buffer[100];
   fgets(buffer, sizeof(buffer), stdin);
   fgets(buffer, sizeof(buffer), stdin);

为不同的输入使用不同的缓冲区:

   char buffer_x[100];
   char buffer_y[100];
   fgets(buffer_x , sizeof(buffer_x), stdin);
   fgets(buffer_y , sizeof(buffer_y), stdin);

4
在第一个样本中,第二个输入将覆盖第一个输入。这就是区别所在。 - Sourav Ghosh
1
如果代码需要在读取第二个结果后保留第一个结果,则应使用不同的缓冲区。 - chux - Reinstate Monica
3
顺便提一下,在使用缓冲区之前,请检查fgets()的返回值。 - chux - Reinstate Monica
1个回答

5

答案取决于您的使用情况。根据逻辑保留要求,两种用法可能都是有效或无效的。

  • In case, the control flow of your program is something like

    read first input
     process first input, never need it after this
    read second input
     carry on
    

    then you're okay with the first approach, reusing the same buffer.

  • In case, you have to make use of the first input even after reading the second one, you need to preserve the first input, like

    read first input
     process first input, but need it later also
    read second input
     carry on 
     do something with first and second inputs
    

    then, you need separate buffers.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接