作者thorita ( )
看板C_and_CPP
标题[问题] C用法的限制???
时间Fri Nov 20 18:17:00 2009
不知道是逻辑上的问题 还是C用法的限制
请大家帮忙解惑一下
程式码如下
01 struct mydata
02 {
03 char name[15];
04 int num;
05 }stu;
06
07 puts("what's ur name >>");
08 gets(stu.name);
09
10 puts("what's ur num >>");
11 scanf("%d",&stu.num);
12
13 printf("num = %d, name = %s ",stu.num,stu.name);
这样很正常
但如果把程式改成这样
puts("what's ur num >>");
scanf("%d",&stu.num);
puts("what's ur name >>");
gets(stu.name);
先输入号码後输入名字
这样反而会发生 无法输入名字的状况
当然我知道可以将 gets 换 scanf
但是为什麽放在这边就不行
是逻辑上的问题吗?
谢谢
--
新手本版第一篇
请多包含....
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 219.68.80.164
1F:推 VictorTom:第二种写法的後面多一行 getchar(); 试试.... 11/20 18:18
2F:→ VictorTom:像是原生数值型态与char string交互输入时的老问题@_@" 11/20 18:19
3F:推 Bencrie:scanf("%d\n",&stu.num); 这样呢? 11/20 18:19
4F:→ VictorTom:忘了还有楼上这一招^^|| 11/20 18:20
5F:→ thorita:B大 你的方法跑出来很妙喔~ :P 会变成先输入名字,然後才 11/20 18:28
6F:→ thorita:跑出说 What's ur name >> XD 11/20 18:29
7F:→ thorita:V大 可以问一下理由吗?为什麽会这样? 11/20 18:34
8F:推 VictorTom:因为换行也是某种字元, 就像我2F推的那样....@_@" 11/20 20:21
9F:推 mepass:scanf不会读enter 就会留给下一个函式读 11/20 20:33
10F:推 VictorTom:其实小弟我不懂的是, Enter塞回去给下一个读的状况, 那 11/20 20:43
11F:→ VictorTom:我後面如果都是读数字的scanf为什麽就不会Enter塞住?? 11/20 20:44
12F:→ VictorTom:应该有些人有经验, 要读数字时喂英文字, 就塞爆了@_@" 11/20 20:44
13F:推 twotwoone:只要有enter就能让gets()终止,这是其本质。 11/20 21:21
14F:→ twotwoone:而scanf的本质是去输入缓冲区做一个正规表示?的抓取 11/20 21:22
15F:→ twotwoone:你写 scanf("1"); 时,是要抓完1,他也只会抓1,其他不 11/20 21:23
16F:→ twotwoone:会去改变,留在原地。即使你心里想说enter是过去式了 11/20 21:24