天天看點

c++中stringstream變量的使用

stringstream在接受一個字元串流輸入後,需要clear方能再次接受輸入并使用,str("")用來清空緩存在stringstream中的内容。

正确代碼:

#include <iostream>
#include <string>
#include <stdlib.h>

int main(int argc, char* argv[]) {
	std::stringstream ss;
	int a, b, c;
	ss << "4";
	ss >> a;
	ss.clear();
	ss << "2";
	ss >> b;
	ss.clear();
	ss.str("");
	ss << "567";
	ss >> c;
	std::cout << a << " " << b << " " << c << std::endl;
	system("pause");
	return 0;
}
           

輸出結果:4 2 567

以上代碼若沒有ss.clear()的話輸出結果:4 -858993460 -858993460

參考連結:

stringstream中的clear()與str()

-----------------------------------------------2020.2.12-----------------------------------------------

探究stringstream持續向一字元串變量傳遞值是否會影響原意:

int main(){
	std::stringstream ss;
	std::string str;
	ss << 11;
	ss >> str;
	std::cout << str << std::endl;
	ss.clear();
	ss.str("");
	//str = "";
	ss << 22;
	ss >> str;
	std::cout << str << std::endl;
	return 0;
}
           

無論中間的注釋行是否被運作過,結果均是11換行22。證明在下次傳遞字元串值後字元串變量中的值被擦除後再寫上了。

繼續閱讀