面向行的输入 getline()和get()的使用

1.getline()的使用:

char name[20]; 
cin >> name;  

如果用这种方式输入,当碰到输入诸如Dirk Hamernose这样分开的名字时,就会出现问题。只有使用


char name[20]; 
cin.getline(name,20);

这种方法可以解决输入复杂名字的情况。

     getline()函数每次读取一行,它通过换行符来确定行尾,但不保存换行符。

string list[5];
for(int i = 0; i < 5; i++)
   getline(cin, list[i]);


2.get()的使用:

char name[20],dessert[20];
cin.get(name,20);
cin.get(dessert,20);

这种情况,在输入name的时候会是正常的,但是由于get()函数保存换行符,所以下次再使用get()函数时,碰到的是换行符,会认为已到达行尾,而没有发现任何可读取的内容,所以会出问题,正确的解决方法如下:


char name[20], dessert[20];
cin.get(name,20);
cin.get();
cin.get(dessert,20);


通过加入cin.get();这句,cin.get();可以读取下一个字符,把换行符读取了,就可以解决该问题。还有一种方法就是上述方法的简写:

char name[20],dessert[20];
cin.get(name,20).get();
cin.get(dessert,20);

get()函数的妙用:

int year;
char address[80];
cout << "input the year: ";
cin >> year;
cout << "input the address: ";
cin.getline(address,80);
cout << "year is " << year << " and address is " << address << endl;

这种情况下,就会出问题,在输入year之后,然后调用getline()看到换行符后,讲认为读取的是一个空行,就把空字符串赋给address,就显示不正常了,正确解决方法如下:

int year;
char address[80];
cout << "input the year: ";
cin >> year;
cin.get();
cout << "input the address: ";
cin.getline(address,80);
cout << "year is " << year << " and address is " << address << endl;

或者

int year;
char address[80];
cout << "input the year: ";
(cin >> year).get();
cout << "input the address: ";
cin.getline(address,80);
cout << "year is " << year << " and address is " << address << endl;





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值