解释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()
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP