免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2579 | 回复: 2
打印 上一主题 下一主题

[C++] [求解释]cin和scanf有一样的缺点: 类型不匹配时退出 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-03 14:13 |只看该作者 |倒序浏览
10可用积分
1. 如果一次输入的数据超过一个,它会自动分配给下一次的cin或者scanf,不会自动取第一个数字
> vi io.c
"io.c" [New file]
#include<stdio.h>
int main(void){
int a,b,c;
printf("input a\n");
scanf("%d",&a);
printf("input b\n");
scanf("%d",&b);
printf("input c\n");
scanf("%d",&c);
printf("%d,%d,%d\n");
return 0;
}

> vi io.cpp
#include<iostream>
using namespace std;
int main(void){
  int a,b,c;
  cout<<"input a\n";
  cin>>a;
  cout<<"input b\n";
  cin>>b;
  count<<input c\n";
  cin>>c;
  cout<<a<<","<<b<<","<<c<<"\n";
  return 0;
}

上面两个程序,运行结果完全一样
> ./a.out
input a
23 4
input b
input c
7
23,4,7

2.如果输入格式非法,那么下一次的cin或者scanf就被取消了。这是为什么呢????????????????????????????????
> ./a.out
input a
e
input b
input c
0,-4196928,5
>                    
这里为什么不在输入了呢? 只是由于第一个cin/scanf类型不匹配,以后的cin/scanf全都得变得无效了?
然后0,-4196928,5又是怎么来的?

环境: solaris8+CC

十分感谢!

最佳答案

查看完整内容

man scanf是这么说的。1 读入非法格式数据时scanf返回,输入缓冲区不会被清空,下一次scanf读的是相同内容。2 0,-4196928,5是随机数,你在scanf之前printf或cout试试,应该是一样的值[ 本帖最后由 ynchnluiti 于 2009-3-3 15:11 编辑 ]

论坛徽章:
3
戌狗
日期:2014-09-10 17:07:162015年辞旧岁徽章
日期:2015-03-03 16:54:15wusuopu
日期:2016-06-17 17:43:45
2 [报告]
发表于 2009-03-03 14:13 |只看该作者
man scanf是这么说的。
These  functions  return  the  number  of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
       The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.  EOF is  also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.


1 读入非法格式数据时scanf返回,输入缓冲区不会被清空,下一次scanf读的是相同内容。
2 0,-4196928,5是随机数,你在scanf之前printf或cout试试,应该是一样的值

[ 本帖最后由 ynchnluiti 于 2009-3-3 15:11 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2009-03-03 14:44 |只看该作者
1,你的逻辑错误为什么要库函数给你摆平?错了自然就得返回,很明显的道理嘛
2,这可能是实现的原因了,我这里是-1078514680,-1078514680,134513388
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP