> 文档中心 > cin.getline和getline区别

cin.getline和getline区别

 1.cin.getline()函数cin.getline(字符数组名,字符个数,结束标志),结束标志可以省略,碰到回车就会停止。
  cin.getline()可以接收空格,直到碰到回车才停止,所以会读取n-1个元素。

#include using namespace std;int main() {  char a[100] ;cout<<"输入的值为:"<<end;    cin.getline(a, 10);    for(int i = 0; i<10;i++)    cout << "输出的值:"<<a[i]<< endl;    return 0;}

用户端输入的字符不足给定的元素个数,则只截取用户的元素,如果用户端输入的字符数目大于给定的,则按照给定的数目截取,空格也算在内。

结果

D:\untitled19\cmake-build-debug\untitled19.exe输入的值:1 2 3456789输出的值:1234567Process finished with exit code 0

2.(1) getline()函数getline(cin, str)  将输入流保存到str中去,过程中空格也一并接收可读取整行,

包括前导和嵌入的空格,并将其存储在字符串对象中。

#include #include  //来导入标准库中的字符串类和相关操作,导入后才能使用string类using namespace std;int main(){    string name;    string city;    cout << "Please enter your name: ";    getline(cin, name);    cout << "Enter the city you live in: ";    getline(cin, city);    cout << "Hello, " << name << endl;    cout << "You live in " << city << endl;    return 0;}

运行结果:

D:\untitled39\cmake-build-debug\untitled39.exe Please enter your name: jan Enter the city you live in: Beijing Hello, janYou live in BeijingProcess finished with exit code 0

  (2) 当同时使用cin和getline时,在输入流cin结束后需要清空缓存,否则下一个读入的并不是用户的输入而是一个回车。 例如:

#include #include  using namespace std;int main(){    string c;    int a;    cin>>a;    getline(cin, c);    cout<<c<<endl;    return 0;}

运行结果:

D:\untitled39\cmake-build-debug\untitled39.exe5Process finished with exit code 0

输入流赋值给a后,本想通过getline获取c,却没有机会再进行输入了,这是因为cin之后的回车交给了c, 程序结束

 解决方法是插入一个函数用来接收\n,然后再调用自己的getline函数来接收之后的string c;

测试结果: 

D:\untitled39\cmake-build-debug\untitled39.exe2bbProcess finished with exit code 0