C语言的输入输出的方式 :scanf()&printf() 和 getchar()&putchar()和 gets()&puts() 基本用法

(一)scanf()&printf()

C语言的输入输出通常使用scanf()、printf()函数

scanf() 函数用于从标准输入(键盘)读取并格式化,

printf() 函数发送格式化输出到标准输出(屏幕)。使用printf()函数打印时需要引用头文件,并加上#incldue的预处理命令

例:

#include

int main()
{
   int input;
   //输入
   scanf( "%d", &input);
   //输出
   printf( "%d\n", input);
   
   return 0;
}

(二) getchar()&putchar()

int getchar(void)可以在屏幕上读取下一个可用的字符,并把它返回为一个整数,这个函数在同一个时间内只会读取一个单一的字符。您可以在循环内使用这个方法,以便从屏幕上读取多个字符。

int putchar(int c) 函数把字符输出到屏幕上,并返回相同的字符。这个函数在同一个时间内只会输出一个单一的字符。您可以在循环内使用这个方法,以便在屏幕上输出多个字符。

例1:

#include

int main()
{
	int input;
	while ((input=getchar()) != EOF)
	{
		putchar(input);
	}
	return 0;
}

运行结果:

C语言的输入输出的方式 :scanf()&printf() 和 getchar()&putchar()和 gets()&puts() 基本用法_第1张图片

(三) gets()&puts()

char *gets(char *s) 函数从 stdin 读取一行到 s 所指向的缓冲区,直到一个终止符或 EOF。

int puts(const char *s) 函数把字符串 s 和一个尾随的换行符写入到 stdout

需要注意的是,scanf()在读取字符串时,输入时遇到空格就不再读取,遇到空格默认为结束

而gets遇到回车才认为结束,如果要输入带有空格的字符时(haha hello!),应该用gets;

gets和scanf共同点:都会自动在字符串后面加上'\0'

例1:

#include 

main()

{

char ch1[10],ch2[10];

scanf("%s",ch1);

gets(ch2);

}

依次输入 haha hello!  haha hello!,ch1="haha\0",ch2="haha hello!\0"   

#include 

main()

{

char ch1[10],ch2[10],c1,c2;

scanf("%s",ch1);

c1=getchar();

gets(ch2);

c2=getchar();

}

分别输入hello回车  hello回车    ch1="hello\0"  c1='\n'  ch2="hello\0"  c2则还需要输入

scanf :当遇到回车,空格和tab键会自动在字符串后面添加’\0’,但是回车,空格和tab键仍会留在输入的缓冲区中。

gets:读取字符串,用回车结束输入,可接受回车键之前输入的所有字符,并用’\n’替代 ‘\0’,(gets遇到’\n’后将其翻译为结束符’\0’(其ASCII码为0)),回车键不会留在输入缓冲区中。

#include 
int main(void)
{
    char name[] = "李四";
    printf("%s\n", name);  //用printf输出
    puts(name);  //用puts()输出
    puts("王五");  //直接输出字符串
    return 0;
}

C语言的输入输出的方式 :scanf()&printf() 和 getchar()&putchar()和 gets()&puts() 基本用法_第2张图片 

可以看出来,用 puts() 函数连换行符 '\n' 都省了,使用 puts() 显示字符串时,系统会自动在其后添加一个换行符, 而且puts可以直接输出字符串

但是 puts() 和 printf() 相比也有一个小小的缺陷,就是如果 puts() 后面的参数是字符指针变量或字符数组,那么括号中除了字符指针变量名或字符数组名之外什么都不能写。比如 printf() 可以这样写:

printf("输出结果是:%s\n", str);

而 puts() 就不能使用如下写法:

puts(输出结果是:str);

因此,puts() 虽然简单、方便,但也仅限于输出字符串,功能还是没有 printf() 强大。

你可能感兴趣的:(c语言,算法,开发语言)