源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

在输入输出字符串时scanf(),printf()和gets(),puts()的区别浅谈

  • 时间:2022-05-12 14:54 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:在输入输出字符串时scanf(),printf()和gets(),puts()的区别浅谈
1.scanf("%s",str)和gets(str) scanf("%s",str)和gets(str)均可用于输入字符串到字符数组变量str,但scanf("%s",str)只读到输入字符的空格或回车处,而gets(str)读到回车处结束,所以当句子中单词由空格分开时要用后者来输入,如下图所示: [img]http://files.jb51.net/file_images/article/201302/2013228163036556.png[/img] 需要强调一点,scanf("%s",str)在遇到'\n'(回车)或' '(空格)时输入结束,但'\n'(回车)或' '(空格)停留在出入缓冲区,如处理不慎会影响下面的输入;gets(str)遇到'\n'(回车)时输入结束,但'\n'(回车)已被替换为'\0',存储于字符串中,输入缓冲中没有遗留的'\n'(回车),不会影响后续的输入。测试程序的代码为:
[u]复制代码[/u] 代码如下:
View Code #include<iostream> #include<stdio.h> using namespace std; int main() {   //freopen("//home//jack//jack.txt","r",stdin);   char str[80];   char ch;   cout<<"1、请输入一个没有空格的字符串:"<<endl;   scanf("%s",str);   cout<<"用scanf(\"%s\",str)输入的字符串为:"<<str<<endl;   cout<<"再输入一次作为对比:"<<endl;   while((ch=getchar())!='\n'&&ch!=EOF);   gets(str);   cout<<"用gets(str)输入的字符串为:"<<str<<endl;   cout<<"2、请输入一个有空格的字符串:"<<endl;   scanf("%s",str);   cout<<"用scanf(\"%s\",str)输入的字符串为:"<<str<<endl;   cout<<"再输入一次作为对比:"<<endl;   while((ch=getchar())!='\n'&&ch!=EOF);   gets(str);   cout<<"用gets(str)输入的字符串为:"<<str<<endl;   return 0; }
其中while((ch=getchar())!='\n'&&ch!=EOF);是处理输入缓存中的遗留的办法;fflush(stdin)方法对某些编译器不适用,不是标准C支持的函数。 2、printf(“%s”,str)和puts(str) 先看如下代码:
[u]复制代码[/u] 代码如下:
View Code #include<iostream> #include<stdio.h> using namespace std; int main() {   //freopen("//home//jack//jack.txt","r",stdin);   char str1[80]="hello";   cout<<"用printf(\"%s\",str1)输出的字符串为:";   printf("%s",str1);   cout<<"用puts(str1)输出的字符串为: ";   puts(str1);   char str2[80]="hello world";   cout<<"用printf(\"%s\",str2)输出的字符串为: ";   printf("%s",str2);   cout<<"用puts(str2)输出的字符串为: ";   puts(str2);   return 0; }
[img]http://files.jb51.net/file_images/article/201302/2013228163241651.png[/img] 从运行结果可以看出,printf(“%s”,str)和puts(str)均是输出到'\0'结束,遇到空格不停,但puts(str)会在结尾输出'\n',printf(“%s”,str)不会换行。printf(“%s\n”,str)可以替换puts(str)。 完。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部