与fgets和sscanf [英] fgets and sscanf
问题描述
此code被认为能获得从其中finput和排序,并得到要被排序的整数的数的文件中的第一个整数文件整数和后面的整数是要排序的整数。我不明白如何与fgets和sscanf共同努力。有人可以解释这个code如何与fgets和sscanf工作?
FILE * finput;
为int * array_int,C1,no_elem;
焦炭numlines [500];与fgets(numlines,500,finput);
array_int =(INT *)malloc的(的sizeof(int)的* no_elem);
如果((的sscanf(numlines,%d个,&放大器; no_elem)== 1)及;&放大器;!array_int = NULL)
{
为(C1 = 0;!与fgets(numlines,500,finput)= NULL;)
{
如果(sscanf的(numlines,%D,&安培; array_int [C1])== 1)
{
++ C1;
}
}
}
与fgets
从文件的字符串(即文本行)。
的sscanf
分析基础上,格式字符串的字符串。它是反向的sprintf
。在< X>的printf
和匹配< X> scanf函数
函数允许格式化输出和输入相应的,具有标准格式字符串。例如,%D
表示有符号整数,并在&LT环境; X> scanf函数
它意思是读入下一参数在以下参数列表(您的数组成员在您的案件)。
您可以直接从文件中使用解析的fscanf
,但使用与fgets
+ 的sscanf
,而不是允许更多的灵活性,可能是更安全的。
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;
}
}
}
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.
这篇关于与fgets和sscanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!