函数定义:
getline(istream &in, string &s)
作用:
- 在C++中用 string 类型进行终端输入字符串时,解决无法输入带有空格的字符串的问题。
功能:
从输入流中读入字符,存到string变量,直到出现以下情况为止:
- 读入了文件结束标志'\0'
- 读到一个新行'\n'
- 达到字符串的最大长度
如果getline没有读入字符,将返回false,可用于判断文本文件是否结束
使用方式:
普通:
1 string str; 2 getline(cin,str); 3 cout<<str;
文本文件的输入:
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 5 using namespace std; 6 7 int main() 8 9 { 10 string buff; 11 ifstream infile; 12 ofstream outfile; 13 cout<<"Input file name: "<<endl; 14 cin>>buff; 15 infile.open(buff.c_str()); 16 17 if(!infile) 18 cout<<"error"<<buff<<endl; 19 20 cout<<"Input outfile name: "<<endl; 21 cin>>buff; 22 outfile.open(buff.c_str()); 23 24 while(getline(infile, buff)) 25 outfile<<buff<<endl; 26 27 infile.close(); 28 outfile.close(); 29 return 0; 30 }
参考:
https://blog.csdn.net/slience_perseverance/article/details/19819601