C - 在函数中使用 fgets() 从标准输入读取行

标签 c function fgets

我正在尝试使用 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/

相关文章:

c++ - OpenGL Nvidia 驱动程序 259.12 纹理不工作

c - 用C中的另一个字符串替换字符串中的char

c - 如何在 C 中读取字符数组并通过错误检查将其转换为整数?

JavaScript 切换奇怪的行为

c - 使用 fgets 从文件读取 Seg Failure 错误

c - fscanf 问题 - 无法从文件中提取字符串

c - 从 C 中的其他函数中释放指针

c - 从指针到 char 返回正确的变音字符?

c++ - 在priority_queue中使用greater<char>()

function - Perl - getlogin、getpwuid 和 $<