解釋C語言中無格式輸入輸出函式


無格式輸入輸出函式讀取使用者傳送的單個輸入,並允許在控制檯顯示該值作為輸出。

無格式輸入函式

下面解釋了C程式語言中的無格式輸入函式:

getchar()

它從鍵盤讀取一個字元。

getchar() 函式的語法如下:

Variablename=getchar();

例如,

Char a;
a = getchar();

示例程式

以下是getchar()函式的C程式:

 線上演示

#include<stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("file.txt","w"); //open the file in write mode
   printf("enter the text then press cntrl Z:
");    while((ch = getchar())!=EOF){       putc(ch,fp);    }    fclose(fp);    fp=fopen("file.txt","r");    printf("text on the file:
");    while ((ch=getc(fp))!=EOF){       if(fp){          char word[100];          while(fscanf(fp,"%s",word)!=EOF) // read words from file{             printf("%s
", word); // print each word on separate lines.          }          fclose(fp); // close file.       }else{          printf("file doesnot exist");          // then tells the user that the file does not exist.       }    }    return 0; }

輸出

執行上述程式時,會產生以下結果:

enter the text then press cntrl Z:
This is an example program on getchar()
^Z
text on the file:
This
is
an
example
program
on
getchar()

gets()

它從鍵盤讀取一個字串

gets() 函式的語法如下:

gets(variablename);

示例程式

 線上演示

#include<stdio.h>
#include<string.h>
main(){
   char str[10];
   printf("Enter your name: 
");    gets(str);    printf("Hello %s welcome to Tutorialspoint", str); }

輸出

Enter your name:
Madhu
Hello Madhu welcome to Tutorialspoint

無格式輸出函式

C程式語言中的無格式輸出函式如下:

putchar()

它在監視器上顯示一個字元。

putchar() 函式的語法如下:

Putchar(variablename);

例如,

Putchar(‘a’);

puts()

它在監視器上顯示一個字串。

puts() 函式的語法如下:

puts(variablename);

例如,

puts("tutorial");

無格式輸入輸出示例程式

以下是putc和getc函式的C程式:

 線上演示

#include <stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w");
   printf("enter the text.press cntrl Z:
");    while((ch = getchar())!=EOF){       putc(ch,fp);    }    fclose(fp);    fp=fopen("std1.txt","r");    printf("text on the file:
");    while ((ch=getc(fp))!=EOF){       putchar(ch);    }    fclose(fp);    return 0; }

輸出

執行上述程式時,會產生以下結果:

enter the text.press cntrl Z:
This is an example program on putchar()
^Z
text on the file:
This is an example program on putchar()

更新於: 2024年6月20日

7K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告