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()函数的详细用法。
str()是C++中stringstream类的关键成员,它可以用于获取或设置字符串流中的字符串。在示例中,str()函数分别展示了如何获取流中的字符串赋值给变量,以及如何设置流的初始字符串后再进行读取操作。
4302

被折叠的 条评论
为什么被折叠?



