获取流位置
– tellg() / tellp() 可以用于获取输入 / 输出流位置 (pos_type 类型 )
– 两个方法可能会失败,此时返回 pos_type(-1)
**tellp()**返回当前关联的 streambuf 对象的输出位置指示器。
若出现失败则为 pos_type(-1) 。
示例:
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream s;
std::cout << s.tellp() << '\n';
s << 'h';
std::cout << s.tellp() << '\n';
s << "ello, world ";
std::cout << s.tellp() << '\n';
s << 3.14 << '\n';
std::cout << s.tellp() << '\n' << s.str();
}
输出:
0
1
13
18
hello, world 3.14
tellg()返回当前关联的 streambuf 对象的输入位置指示器。
成功时为获取指针的当前位置,失败时为 pos_type(-1) 。
示例:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string str = "Hello, world";
std::istringstream in(str);
std::string word;
in >> word;
std::cout << "After reading the word \"" << word
<< "\" tellg() returns " << in.tellg() << '\n';
}
输出:
After reading the word "Hello," tellg() returns 6
设置流位置
– seekg() / seekp() 用于设置输入 / 输出流的位置
– 这两个方法分别有两个重载版本:
● 设置绝对位置:传入 pos_type 进行设置
● 设置相对位置:通过偏移量(字符个数 ios_base::beg ) + 流位置符号的方式设置
– ios_base::beg
– ios_base::cur
– ios_base::end
参数
pos - 设置输入位置指示器到的绝对位置。
off - 设置输入位置指示器到的相对位置。
dir - 定义应用相对偏移到的基位置。它能为下列常量之一:
常量 解释
beg 流的开始
end 流的结尾
cur 流位置指示器的当前位置
示例:
basic_istream& seekg( pos_type pos );
basic_istream& seekg( off_type off, std::ios_base::seekdir dir);
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string str = "Hello, world";
std::istringstream in(str);
std::string word1, word2;
in >> word1;
in.seekg(0); // 回溯
in >> word2;
std::cout << "word1 = " << word1 << '\n'
<< "word2 = " << word2 << '\n';
}
输出:
word1 = Hello,
word2 = Hello,
basic_ostream& seekp( pos_type pos );
basic_ostream& seekp( off_type off, std::ios_base::seekdir dir );
示例:
#include <sstream>
#include <iostream>
int main()
{
std::ostringstream os("hello, world");
os.seekp(7);
os << 'W';
os.seekp(0, std::ios_base::end);
os << '!';
os.seekp(0);
os << 'H';
std::cout << os.str() << '\n';
}
输出:
Hello, World!