stringstream c++

320 阅读1分钟

Basic methods are:

  1. clear()- To clear the stream.
  2. str()- To get and set string object whose content is present in the stream. 
  3. operator <<- Add a string to the stringstream object. 
  4. operator >>- Read something from the stringstream object.

image.png stringstream通常是用來做資料轉換的,用於字串與其他變數型別的轉換,相比c庫的轉換,它更加安全,自動和直接。

就好像它是像 cin ,cout这样的流。

可以使用<<和>> 这样的流符,直接对stringstream进行更改.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
	stringstream ss;
	ss << "hello ";//写入缓冲区,并不会输出,与cout用法一致
	ss << "world!";

	std::cout << ss.str() << std::endl;
	return 0;
}

output:

image.png

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
	stringstream ss;
	ss << "hello " << endl;
	ss << "world!";

	std::cout << ss.str() << std::endl;
	return 0;
}

output:

image.png

#include <iostream>
#include <sstream>
using namespace std;
int main(void)
{
    double pi = 3.141592653589793;
    float dollar = 1.00;
    int dozen = 12;
    int number = 35;
    stringstream ss;
    ss << "dozen: " << dozen << endl;
    //显示小数
    ss.setf(ios::fixed);
    //显示2位小数
    ss.precision(2);
    ss << "dollar: " << dollar << endl;
    //显示10位小数
    ss.precision(10);
    ss << "pi: " << pi << endl;
    //按十六进制显示整数
    ss.unsetf(ios_base::dec);
    ss.setf(ios::hex);
    ss << "number: " << number << endl;
    string text = ss.str();
    cout << text << endl;
    return 0;
}

output:

image.png

string转int

1、使用stringstream来实现

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
    int a;
    string s;
    stringstream ss;
    s = "123";
    ss << s;
    ss >> a;
    cout << a << endl;
}
// out: 123

2、也有使用atoi的方法

#include <iostream>
using namespace std;
int main() {
    int a;
    string s;
    s = "123456";
    a = atoi(s.c_str());
    cout << a << endl;

}
// out:123456

统计单词数量

#include <iostream>
#include <sstream>
#include<string>
using namespace std;

int countWords(string str)
{
	stringstream s(str);
	string word;

	int count = 0;
	while (s >> word)
		count++;
	return count;
}
int main()
{
	string s = "How old are you, John?";
	cout << " Number of words are: " << countWords(s);
	return 0;
}

output:

image.png