吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C 中的 scanf() 和 fscanf()

C 中的 scanf() 和 fscanf()

来源:网络 | 更新时间:2022-01-08 20:08:13
在 C 语言中,scanf()函数用于从标准输入读取格式化输入。它返回写入其中的字符的总数,否则返回负值。 语法:
int scanf(const char *characters_set)
我们中的许多人都知道 scanf 的传统用途。好吧,这里有一些鲜为人知的事实 如何只读取我们需要的输入的一部分? 例如,考虑一些仅包含字符后跟整数或浮点数的输入流。我们只需要扫描那个整数或浮点数。  例子:
Input: "this is the value 100", 
Output: value read is 100
Input : "this is the value 21.2", 
Output : value read is 21.2 
// 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 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 从 FILE 指针 (ptr) 指向的文件中读取,而不是从输入流中读取。 返回值:如果不成功,则返回零。否则,如果成功,则返回输入字符串。 示例:考虑以下文本文件 abc.txt 
NAME    AGE   CITY
abc     12    hyderbad
bef     25    delhi
cce     65    bangalore
现在,我们只想读取上述文本文件的城市字段,忽略所有其他字段。fscanf 和上面提到的技巧的组合很容易做到这一点 
// C Program to demonstrat 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 hyderbad
bef 25 delhi
cce 65 bangalore */
char buf[100];
while (fscanf(ptr, "%*s %*s %s ", buf) == 1)
printf("%sn", buf);

return 0;
}
输出
CITY
hyderbad
delhi
bangalore
   

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com