C++ 输入函数getline(cin,str) 与cin.getline(str,int)区别

来源:互联网 发布:mac安装win10激活工具 编辑:程序博客网 时间:2024/05/17 20:23

cin.getline()函数是处理数组字符串的,其原型为cin.getline(char * , int),第一个参数为一个char指针,第二个参数为数组字符串长度。

getline(cin,str)函数是处理string类的函数。第二个参数为string类型的变量。

实例:

#include <iostream>
#include <string>
using namespace std;
const int SIZE=20;

int main()
{
string str;
cout<<"string method:"<<endl;
getline(cin,str);
cout<<"the string is:"<<endl;
cout<<str<<endl;

cin.get();//接受最后一个结束符

char chs[SIZE];
cout<<"char * method:"<<endl;
cin.getline(chs,20);
cout<<"the string is:"<<endl;
cout<<chs<<endl;

return 0;
}

运行结果:

string method:
Hello String

the string is:
Hello String
char * method:
Hello Char *
the string is:
Hello Char *

注:getline(cin,str);处理后还留有结束符在输入流中,故需要使用cin.get();//接受最后一个结束符,才能接受后面得输入值。


要注意的是getline还可以输入空格,这个很重要

0 0
原创粉丝点击