c语言getline与gets,C/C++之键盘输入函数(scanf、gets、getchar、getline、cin、cin.get())...

1. scanf函数

scanf()可以接收多种格式的数据,遇到回车,tab,空格时,输入结束;

scanf()保留回车符号,当连续两次调用scanf时,会直接读入上一次结束scanf时的回车符号“\n”  (0x0a);   没有将回车键屏蔽

#include #include #include #include

using namespacestd;

int main(int argc, char**argv)

{

char buf[100];

scanf("%s", buf);

printf("first input:%s\n", buf);

charret;

scanf("%c", &ret);

printf("second input:0x%x\n", ret);

return 0;

}

执行后:

test

first input:test

second input:0xa

再次scanf的时候,读取出来一个回车符('\n')(0x0a);

当输入字符串中带有空格时:

test space //输入带有空格的字符串

first input:test

second input:space

此时只提示输入一次,第二次执行scanf时候,直接读取空格之后的字符串;

2.gets()

函数原型:char *gets(char *string)

1.和scanf类似,但是遇到空格、Tab时,不会结束写入,仅当遇到回车时结束写入;

2.将回车键屏蔽,再次调用scanf函数时,不会读取到回车键

#include #include #include #include

using namespacestd;

int main(int argc, char**argv)

{

char buf[100];

gets(buf);

printf("first input:%s\n", buf);

chartest;

scanf("%c", &test);

printf("second input:0x%x\n", test);

return 0;

}

运行结果:

tttt  //键入无空格字符串

first input:tttt

yyyyy

second input:0x79  //此时不是0x0a,表示再次读取到的字符不是回车符,second input:y

键入带有空格的字符串运行结果:

tttt yyyy    //键入有空格的字符串

first input:tttt yyyy  //打印正常

uuuuuu

second input:0x75  //由于gets屏蔽了回车键,导致这里获取的不是"\n"second input:u

3.getchar()

仅仅返回键入的第一个字符,不会屏蔽回车符;

键入字符大于1时,再次获取时,会继续读取剩余的字符;

#include #include #include #include

using namespacestd;

int main(int argc, char**argv)

{

chartest;

test =getchar();

printf("first input:%c\n", test);

test =getchar();

printf("second input:0x%x\n", test);

return 0;

}

键入一个字符,执行结果:

t      //键入一个字符,再次getchar时,读入到的是回车符;

first input:t

second input:0xa

键入多个字符时,执行结果:

tyt

first input:t

second input:0x79  //键入多个字符时,再次getchar时,直接读入剩余的字符;second input:y

以上是C语言中的输入函数;

----------------------------------------以下是C++键入函数----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1. cin

和scanf一样,遇到空格,Tab,回车都结束;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值