cin.getline()函数与getline的区别:
处理数组字符串的,其原型为cin.getline(char*,int),第一个参数为指针,第二个参数为数组字符串长度,还能读入空格以及其他字符。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; }
- 实例二:
#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 *