我写了下面的代码来从终端窗口读取一行,问题是代码陷入无限循环.行/句子的长度是未定义的,因此我计划将其分成几部分读入缓冲区,然后将其连接到另一个字符串,该字符串可以通过realloc
相应的方式进行扩展.有人可以发现我的错误或建议更好的方法来实现这个目标吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
use*_*313 24
这里是一个串联解决方案:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10
int main() {
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);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你对fgets的回报有错误的想法.看看这个:http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
它在找到EOF字符时返回null.尝试运行上面的程序并按CTRL + D(或任何组合是你的EOF字符),循环将成功退出.
您想如何检测输入结束?新队?Dot(你说的句子xD)?
归档时间: |
|
查看次数: |
181631 次 |
最近记录: |