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


scanf() 函数

scanf() 函数用于以 C 语言格式从 stdin 中读取输入。它会返回写入它的整个字符数;如果未写任何字符,则返回负值。

以下是 C 语言中 scanf() 的语法:

int scanf(const char *characters_set)

以下是 C 语言中 scanf() 的示例:

示例

 实时演示

#include <stdio.h>
int main () {
   char s[20];
   printf("Enter a string : ");
   scanf("%s", s);
   printf("
Entered string : %s
", s);    return(0); }

输出

Enter a string : Peter!
Entered string : Peter!

fscanf() 函数

fscanf() 函数用于从 C 语言中给定流中读取格式化输入。如果失败,它将返回零。否则,如果成功,它将返回输入字符串。

以下是 C 语言中 fscanf() 的语法:

int fscanf(FILE *stream_name, const char *set_of_characters)

以下是 C 语言中 fscanf() 的示例:

示例

 实时演示

#include <stdio.h>
#include <stdlib.h>
int main () {
   char str1[10];
   int year;
   FILE * fp;
   fp = fopen ("file.txt", "w+");
   fputs("This is demo text!", fp);
   rewind(fp);
   fscanf(fp, "%s", str1);
   printf("First word = 
%s
", str1 );    fclose(fp);    return(0); }

输出

First word =
This

更新于:2020-6-24

2K+ 浏览

启动你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.