C/C++ review1 -- cin, scanf, getchar, gets()

Here, I want to summarize input objects.

 

1, The cin is the input object in c++. The syntax is as follows,

 

int x1;

int x2;

 

cin >> x1 >> x2;

 

The input will be "3 space 4 Enter". Only space can be used here. Colon "," can not be used to seperated them.

 

char arr[100];

 

cin >> arr;

 

If you input “Hello world!”, cout << arr >>endl will show you only "Hello". What happens?

The string "Hello world!" will be stored in cashe when you type "Hello world!" on screen. Then cin will read this string from cashe. The data reading will stop when cin encounters space, TAB and Enter. So, cin only read "Hello" to arr, then stop.

 

If you try:

 

char arr[100];

 

cin >> arr;

cout << arr << endl;

cin >> arr;

cout << arr << endl;

 

If you input "Hello world!", you will get:

Hello

world!

 

Because the first cin get "Hello" then stop and the second cin will get "world!" from cache. It won't let you input from screen again.

 

2, The scanf has the similar features as cin. But its input format is a little different, as follows:

 

int x1;

int x2;

 

scanf("%d, %d", &x1, &x2)

 

The input will be "3, 4 Enter".

 

If the syntax is: scanf("%d%d", &x1, &x2), your input should be "34 Enter" or "3 4 Enter".

 

3, The getchar is used to get a character from screen. Its syntax is:

 

char c;

 

c = getchar();

 

4, The gets is used to get string from screen.

 

char c[100];

 

gets(c);

 

It can contain space. If you input "Hello world!", its output is "Hello world!"

 

That is all for today. I need to keep reading c++ primer now.

 

Before using getchar, fflush(stdin) can be called to clean cache, then you can always get input screen. For cin, I checked, it seems fflush(stdin) doesn't work with it.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值