c++中一串字符数组的输入

solution 1:cin

 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4 
 5     char str[10];
 6     cout << "enter a sentence:" << endl;
 7     while (cin >> str)
 8         cout << str << endl;
 9 
10     return 0;
11 }
cin实例

 

  以输入“abc def g”为例该程序执行结果为:

1 enter a sentence:
2 abc def g
3 abc
4 def
5 g
cin实例执行结果

  执行过程,由于abc、def后为空格,g后为回车,因此cin先将abc读入给str然后打印,依此类推。cin将空格、回车当作不同字符串之间的间隔。

 

solution 2:cin.get()

  有3个参数的get函数

      cin.get(ch,n,'\n');

  1.读取n-1个字符(包含空格),赋给指定的字符数组ch;

  2.如果在读取n-1个字符之前,遇到指定的终止字符'\n',则提前结束读取;(如果第3个参数没有指定,则默认为'\n'。

  3.读取成功返回非0值(真),如失败(遇文件结束符)则返回0值(假)。

 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     
 5     char ch[20];
 6     cout << "enter a sentence" << endl;
 7     cin.get(ch, 10, 'o');//指定终止符为'o'
 8     cout << ch << endl;
 9 
10     return 0;
11 }
cin.get()实例

以输入“We are good friends”为例该程序执行结果为:

1 enter a sentence:
2 We are good friends.
3 We are g
cin.get()实例执行结果

 

solution 3:cin.getline()

  其参数配置与cin.get()完全一致。

 

重点:getline与get的区别

1.getline遇到终止字符时结束,缓冲区指针移到终止标志字符之后。

2.get遇到终止字符停止读取,指针不移动。

根据以上例子

We are g↑ood friends.     cin.get()

We are good friends.  cin.getline()

转载于:https://www.cnblogs.com/jerrywyj/p/3515745.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值