我正在尝试使用 fgets() 从 stdin 读取行,我想在我的函数中使用 fgets(),我认为这是问题所在。该字符串的最大长度为 1024 个字符。当我运行此代码时,我收到“段错误(核心转储)”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1025
void print_fgets();
int main()
{
print_select();
return 0;
}
void print_select()
{
char *str;
int length;
while (fgets( str, MAX_SIZE, stdin)!=NULL)
{
length=strlen(str);
if (length==MAX_SIZE-1 && str[length-1]!='\n')
{
printf("Error, line overeached buffer!\n");
return 1;
}
if (str[length-1]=='\n')
str[length-1]='\0';
printf("%s\n", str);
}
}
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1025
int print_select(); /* Use correct name (instead of print_fgets()) */
int main()
{
print_select();
return 0;
}
int print_select() /* Fix. Dhould return int if you have a return <int> statement. */
{
char str[MAX_SIZE]; /* Initialize static memory. */
int length;
while (fgets( str, MAX_SIZE, stdin)!=NULL)
{
length=strlen(str);
if (length==MAX_SIZE-1 && str[length-1]!='\n')
{
printf("Error, line overeached buffer!\n");
return 1;
}
if (str[length-1]=='\n')
{
str[length-1]='\0';
}
printf("%s\n", str);
}
return 0; /* Function may not be returning an int. Return it in those cases. */
}
关于C - 在函数中使用 fgets() 从标准输入读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26718332/