C++ 中的字符串流
在本文中,我们将了解 C++ 中的字符串流。字符串流将字符串对象与字符串相关联。利用这一特性,我们可以像使用 cin 一样从字符串中读取数据。
字符串流有不同的方法。如下所示 −
clear(): 用于清除流
str(): 用于获取和设置流中存在内容的字符串对象
操作符 << : 将一个字符串添加到字符串流中
操作符 >> : 用于从字符串流对象中读取数据。
我们来看两个字符串流的示例。在第一个程序中,我们将单词拆分为单独的字符串。
示例
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str("Hello from the dark side");
string tmp; // A string to store the word on each iteration.
stringstream str_strm(str);
vector<string> words; // Create vector to hold our words
while (str_strm >> tmp) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
for(int i = 0; i<words.size(); i++)
cout << words[i] << endl;
}输出
Hello from the dark side
在这里,我们将使用字符串流将十进制转换为十六进制。
示例
#include<iostream>
#include<sstream>
using namespace std;
main(){
int decimal = 61;
stringstream my_ss;
my_ss << hex << decimal;
string res = my_ss.str();
cout << "The hexadecimal value of 61 is: " << res;
}输出
The hexadecimal value of 61 is: 3d
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP