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


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;
}

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

  两个函数返回值都会丢弃换行符。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM