c - how can I read multiple inputs from stdin in c using fgets
问题描述
I tried this code and the wrote another similar one to read another input but the program read in the second time both the first stdin and the second one (also I used fflush(stdin) instead of fseek() but that didn't work either)
int BUFFERSIZE=100;
char input[BUFFERSIZE];
char *final=malloc(1);
while(fgets(input,BUFFERSIZE-1,stdin))
{
final=realloc(final,strlen(final)+strlen(input)+1);
strcat(final,input);
if(input[strlen(input)-1]=='\n') break;
}
sscanf(final,"%d",&opt);
free(final);
fseek(stdin,0,SEEK_END);
解决方案
You didn't initialize the contents of the final
buffer before the loop. So the first strlen(final)
and strcat(final, input)
are reading an uninitialized string, causing undefined behavior.
int BUFFERSIZE=100;
char input[BUFFERSIZE];
char *final=malloc(1);
*final = 0; // initialize to empty string
while(fgets(input,BUFFERSIZE-1,stdin))
{
final=realloc(final,strlen(final)+strlen(input)+1);
strcat(final,input);
if(input[strlen(input)-1]=='\n') break;
}
sscanf(final,"%d",&opt);
free(final);
推荐阅读
- macos - 我收到“文字中的无效转义序列”错误
- android-studio - 如何在没有互联网的情况下集成android离线地图
- amazon-web-services - 发生错误:进行无服务器部署时收到 KeypairSecretRotationSchedule
- javascript - 使用正则表达式过滤数组列表
- android - SoundPool 加载失败
- json - 使用未知密钥反序列化 Json - ASP.Net Core 3.1
- angular - Workbox with Angular 12 Error: Can't find self.__WB_MANIFEST in your SW source
- c - 重新创建 strrchr() 但在字符串末尾获取额外字符
- c++ - 当 xml 源路径包含特殊字符(如表情符号)时,MSXML2::IXMLDOMDocument2Ptr load() 失败
- intellij-idea - 手动安装 Intellij azure-toolkit-for-intellij.jar 包含无效的插件描述符