如何从用于fgets标准输入读取()? [英] How to read from stdin with fgets()?
本文介绍了如何从用于fgets标准输入读取()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经写了下面的code读取终端窗口行,问题是code陷在一个无限循环。该生产线/句话是不确定的长度,所以我计划在部分读入缓冲区,然后将其串连到另一个字符串,它可以通过的realloc
扩展相应。请可有人发现我的错误或建议实现这一目标的一个更好的办法?
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;#定义BUFFERSIZE 10INT主(INT ARGC,CHAR *的argv [])
{
字符缓冲区[BUFFERSIZE]
的printf(请输入一个信息:\\ n);
而(与fgets(缓冲,BUFFERSIZE,标准输入)!= NULL)
{
的printf(%S \\ n,缓冲区);
}
返回0;
}
解决方案
下面的串联解决方案:
的char *文字=释放calloc(1,1),缓冲[BUFFERSIZE]
的printf(请输入一个信息:\\ n);
而(与fgets(缓冲,BUFFERSIZE,标准输入))/ *与休息^ D或^ Z * /
{
文字=的realloc(文字,strlen的(文本)+ 1 + strlen的(缓冲));
如果(!文)... / *错误处理* /
strcat的(文字,缓冲区); / *注一个的'\\ n'在这里,每次追加* /
的printf(%S \\ n,缓冲区);
}
的printf(\\ NTEXT:\\ n%S,文本);
I've written the following code to read a line from a terminal window, the problem is the code gets stuck in an infinite loop. The line/sentence is of undefined length, therefore I plan to read it in parts into the buffer, then concatenate it to another string which can be extended via realloc
accordingly. Please can somebody spot my mistake or suggest a better way of achieving this?
#include <stdio.h>
#include <string.h>
#define BUFFERSIZE 10
int main (int argc, char *argv[])
{
char buffer[BUFFERSIZE];
printf("Enter a message: \n");
while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
{
printf("%s\n", buffer);
}
return 0;
}
解决方案
here a concatenation solution:
char *text = calloc(1,1), buffer[BUFFERSIZE];
printf("Enter a message: \n");
while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
{
text = realloc( text, strlen(text)+1+strlen(buffer) );
if( !text ) ... /* error handling */
strcat( text, buffer ); /* note a '\n' is appended here everytime */
printf("%s\n", buffer);
}
printf("\ntext:\n%s",text);
这篇关于如何从用于fgets标准输入读取()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文