str()
是C++标准库中stringstream
类的一个成员函数,用于获取或设置字符串流中的字符串。
str()
函数有两种用法:
- 获取字符串流中的字符串。例如:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
ss << "Hello, world!";
string s = ss.str();
cout << s << endl;
return 0;
}
上面的代码中,ss << "Hello, world!";
将字符串"Hello, world!“写入字符串流ss中。然后string s = ss.str();
调用了ss的str()
函数,返回ss中的字符串,并将其赋值给s。最后输出s的值,得到"Hello, world!”。
- 设置字符串流中的字符串。例如:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
ss.str("Hello, world!");
string s;
ss >> s;
cout << s << endl;
return 0;
}
上面的代码中,ss.str("Hello, world!");
调用了ss的str()
函数,将ss中的字符串设置为"Hello, world!“。然后ss >> s;
从ss中读取一个字符串,并将其赋值给s。最后输出s的值,得到"Hello,”。
这就是str()
函数的详细用法。