getline()函数的使用

来源:互联网 发布:电脑如何卸载软件 编辑:程序博客网 时间:2024/06/06 20:50
int counter = 0;
std::fstream file;
file.open(file_path, std::ios::in);


if (!file.is_open())
{
std::cout << "Error opening file: " << file_path << std::endl;
}


std::string line;


std::stringstream ss;


int tmpl_width, tmpl_height;

std::getline(file, line);
ss << line;//把fill文件中的 一行写入line中,下一次则会自动读取下一行

ss >> tmpl_width >> tmpl_height;

getline()函数用于读取文本中的一行内容。把一行的内容放到ss中之后,在把ss中的内容依次给 tmpl_width和tmpl_height;

假如ss中的内容是 32  32//中间有空格,

则ss会根据空格把32  32 赋值给 tmpl_width和tmpl_height;

若是读取到的内容是3232//中间无空格

则执行ss >> tmpl_width >> tmpl_height;后,tmpl_width值是3232,而 tmpl_height的值则是未知的。

同样对于string类型和int类型的也是以空格为界,

假如ss内容是   {'type': 1, 'x': 0, 'y': 0, 'blk': 2, 'bw': 3, 'bh': 3, 'rt0': (0, 0, 3, 3, 1), 'rt1': (3, 0, 3, 3, -1)}

执行此句:ss >> tmp_str >> type >> tmp_str >> tmp_str >> left >> tmp_str >> tmp_str >> top >> tmp_str >> tmp_str >> blks >> tmp_str >> tmp_str >> bw >> tmp_str >> tmp_str >> bh;

则 tmp_str =  {'type':

type=1;//因为type:和1之间有空格,所以到空格终止。

若是两者之间没有空格,则 tmp_str =  {'type': 1, 'x':     //直到遇到第一个空格终止。


0 0
原创粉丝点击