fgets and sscanf

冷暖自知 提交于 2019-12-25 13:43:24

问题


This code is supposed to get integers from a file which is finput and sort it and gets the first integer in the file which is the number of integers to be sorted and the integers that follow are the integers to be sorted. I don't get how fgets and sscanf work together. Can someone explain how fgets and sscanf work in this code?

FILE *finput;
int *array_int, c1, no_elem;
char numlines[500];

fgets(numlines, 500, finput); 
array_int = (int *)malloc(sizeof(int)*no_elem);
if ((sscanf(numlines, "%d", &no_elem) == 1) &&  array_int!= NULL)
{
    for(c1=0; fgets(numlines, 500, finput) != NULL; )  
    {
        if (sscanf(numlines, "%d", &array_int[c1])==1) 
        {
            ++c1;
        }
    }
}

回答1:


fgets gets a string (i.e. a line of text) from the file.

sscanf parses a string based on the format string. It is reverse to sprintf. the <x>printf and matching <x>scanf functions allow formatted output and input accordingly, with a standard format string. For example, "%d" means "signed integer value", and in context of <x>scanf it means "read it into the next parameter in the following list of parameters" (your array member in your case).

You can parse directly from the file using fscanf, but using fgets + sscanf instead allows for more flexibility and might be safer.



来源:https://stackoverflow.com/questions/9858809/fgets-and-sscanf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!