C语言中的scanf()和fscanf()

在C语言中, scanf() 函数用于从标准输入读取格式化输入。它返回写入其中的字符总数,否则返回负值。

null

语法:

int scanf(const char *characters_set)

我们很多人都知道scanf的传统用法。以下是一些鲜为人知的事实

如何只读取我们需要的输入的一部分? 例如,考虑一些只包含字符或整数的输入流。我们只需要扫描整数或浮点。

例子:

Input: "this is the value 100", Output: value read is 100Input : "this is the value 21.2", Output : value read is 21.2 

C

// C program to demonstrate that
// we can ignore some string
// in scanf()
#include <stdio.h>
int main()
{
int a;
scanf ( "This is the value %d" , &a);
printf ( "Input value read : a = %d" , a);
return 0;
}
// Input  : This is the value 100


现在,假设我们不知道前面的字符是什么,但我们肯定知道最后一个值是整数。如何将最后一个值扫描为整数?

下面的解决方案仅在输入字符串没有空格时有效。例如

输入

"blablabla 25"

C

// C program to demonstrate use of *s
#include <stdio.h>
int main()
{
int a;
scanf ( "%*s %d" , &a);
printf ( "Input value read : a=%d" , a);
return 0;
}


输出

Input Value read : 25

解释 :scanf中的%*s用于根据需要忽略某些输入。在这种情况下,它会忽略输入,直到下一个空格或换行符。同样,如果你写%*d,它将忽略整数,直到下一个空格或换行符。

乍一看,上述事实似乎不是一个有用的伎俩。为了理解它的用法,让我们先看看fscanf()。

C语言中的fscanf函数

厌倦了从文件中读取的所有笨拙语法?fscanf来救援了。此函数用于从C语言的给定流中读取格式化输入。

语法:

int fscanf(FILE *ptr, const char *format, ...) 

fscanf从文件指针(ptr)指向的文件中读取,而不是从输入流中读取。

返回值: 如果不成功,则返回零。否则,如果成功,它将返回输入字符串。

例子: 考虑下面的文本文件ABC。txt

NAME    AGE   CITYabc     12    hyderbadbef     25    delhicce     65    bangalore  

现在,我们只想读取上面文本文件的city字段,忽略所有其他字段。fscanf和上述技巧的结合可以轻松实现这一点

C

// C Program to demonstrate fscanf
#include <stdio.h>
// Driver Code
int main()
{
FILE * ptr = fopen ( "abc.txt" , "r" );
if (ptr == NULL) {
printf ( "no such file." );
return 0;
}
/* Assuming that abc.txt has content in below
format
NAME    AGE   CITY
abc     12    hyderabad
bef     25    delhi
cce     65    bangalore */
char buf[100];
while ( fscanf (ptr, "%*s %*s %s " , buf) == 1)
printf ( "%s" , buf);
return 0;
}


输出

CITYhyderabaddelhibangalore 

本文由 Nikhil Chakravartula .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以在上面写一篇文章 写极客。组织 .查看你在GeekSforgeks主页上的文章,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享