+ -
当前位置:首页 → 问答吧 → 100分紧急求助,getline从输入流中删除结束符

100分紧急求助,getline从输入流中删除结束符

时间:2011-12-14

来源:互联网

getline从输入流中删除结束符。
get却把该字符保留在输入流中。
所以读入多行字符时应使用getline函数。

能举个例子说明吗,多谢

作者: longlong2234   发布时间: 2011-12-14

数上有个例子
#include <iostream.h> 
#include <string.h>
const int SIZE=80;
void main() 

char s1[SIZE],s2[SIZE]; 
cout<<"输入一个英语句子:\n"; 
cin>>s1; 
cin.getline(s2,SIZE); 
cout <<"用cin读入的字符串是:"<<s1;
cout<<"字符数:"<<strlen(s1)<<endl;  
  cout <<"用cin.getline读入的字符串是:"<<s2;
cout<<"字符数:"<<strlen(s2)<<endl;
}  
为什么是下面的结果?
本程序的执行示例结果: 
输入一个英语句子: You are a student.
用cin读入的字符串是: You 字符数:3
用cin.getline读入的字符串是: are a student. 字符:15

作者: longlong2234   发布时间: 2011-12-14

http://zhidao.baidu.com/question/19807416.html
讲的很详细, 自己看下

作者: tujiaw   发布时间: 2011-12-14

引用 1 楼 longlong2234 的回复:

数上有个例子
#include <iostream.h>
#include <string.h>
const int SIZE=80;
void main()
{
char s1[SIZE],s2[SIZE];
cout<<"输入一个英语句子:\n";
cin>>s1;
cin.getline(s2,SIZE);
cout <<"用cin读入的字符串是:"<<s……

结果没有问题的

cin>>s1
输入s1为you are a student
cin遇到空格就结束输入了 所以s1="you"

而后面的输入保存在内存当中,作为下一个输入的
getline()可以输入空格的 以换行符结束输入
结果是are a student

作者: elegant87   发布时间: 2011-12-14