声明
C++ 98 中的声明格式
(1) istream& getline (istream& is, string& str, char delim);
(2) istream& getline (istream& is, string& str);
C++11 增加了两个
(3) istream& getline (istream&& is, string& str, char delim);
(4) istream& getline (istream&& is, string& str);
功能
从is中提取一行字符将其存入str中(没有指定delim),或者将is中delim字符之前的字符存入str中(指定了delim)。正确执行is跟str都会被修改。
注意:
1.如果到达了流的结尾或者遇到其它错误该提取操作也会停止。
2.如果找到delim字符,该字符将会被丢弃,并不会存入str中,再次操作也会从delim的下一个字符开始。
输入
is istream对象
str 存储结果的string对象,调用getline之前str中如果有内容,该内容将会被清除。
返回值
is做为返回值。
调用该函数如果发生下列情况,is参数的内部状态可能会被设置。
1. eofbit 输入源字符集到达了结尾。
2. failbit 如果获取的输入并不能作为一个有效的文本对象来解释,is将会保持被调用前参数和内容。注意eofbit也有可能会设置failbit标记。
3.badbit 除了以上以外的其它错误。
另外,以上情况,如果对应的标记被ios::exceptions设置,ios_base::failure类型的异常将会被抛出。
例子
简单的配置文件的解析:
test.txt内容
a=b
c=d
e=f
#include <sstream>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
//
class Config
{
private:
std::map<std::string,std::string> mapKV;
public:
int parser(std::string strfile)
{
std::fstream file;
file.open(strfile.data(),std::ios::in);
if (!file.is_open())
{
std::cout << "open the file failed , file=" << strfile << std::endl;
return -1;
}
std::string strLine;
while(std::getline(file,strLine))
{
std::cout << "get new line , strLine=" << strLine << std::endl;
std::string key,value;
size_t pos = strLine.find("=");
if (pos == std::string::npos)
{
std::cout << "line format error 111, strLine=" << strLine << std::endl;
continue;
}
key = strLine.substr(0,pos);
value = strLine.substr(pos+1);
if (!key.empty() && !value.empty())
{
mapKV[key] = value;
}
else
{
std::cout << "line format error 222, strLine=" << strLine << std::endl;
}
}
file.close();
return 0;
}
};
int main()
{
Config config;
config.parser("test.txt");
return 0;
}
说明 : 本人由于能力所限如果理解有误或者有重大错误,欢迎大家纠正!
原文地址 http://www.cplusplus.com/reference/string/string/getline/?kw=getline