C++ Primer 5th笔记(8)chapter8 类:IO库-string流
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(8)chapter8 类:IO库-string流
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
sstream輸入輸出類繼承自iostream類
. istringstream讀取一個字符串
. ostringstream寫入一個字符串
1. 可以使用iostream類的操作
sstream strm; //一個未綁定的stringstream sstream strm(s); //strm持有一個string s,這個構造函數是explicit strm.str(); //返回一個string的copy strm.str(s); //將string復制進strm,返回voidstringstream構造函數會特別消耗內存,似乎不打算主動釋放內存(或許是為了提高效率),但如果你要在程序中用同一個流,反復讀寫大量的數據,將會造成大量的內存消耗適時地清除一下緩沖 (用 stream.str("") )。
2. 字符串變基本數據類型
/字符串 變 double/
void static ioString1()
{
double n;
string str = “12.5”;
stringstream stream;
stream << str;
stream >> n;
cout << " " << n;
}
3. istringstream
4. ostringstream
void static ioString3(){//初始化輸出字符串流ostr ostringstream ostr("1234");cout << ostr.str() << endl;//輸出1234 ostr.put('5');//字符4頂替了1的位置 cout << ostr.str() << endl;//輸出5234 ostr << "67";//字符串67替代了23的位置,輸出5674 string str = ostr.str();cout << str << endl;}4. istringstream + ostringstream :
struct PersonInfo {string name;vector<string> phones;};// we'll see how to reformat phone numbers in chapter 17// for now just return the string we're givenstatic string format(const string& s) { return s; }vector<PersonInfo> static getData(istream& is){// will hold a line and word from input, respectivelystring line, word;// will hold all the records from the inputvector<PersonInfo> people;// read the input a line at a time until end-of-file (or other error)while (getline(is, line)) {if (line.length() < 2)break;PersonInfo info; // object to hold this record's dataistringstream record(line); // bind record to the line we just readrecord >> info.name; // read the namewhile (record >> word) // read the phone numbers info.phones.push_back(word); // and store thempeople.push_back(info); // append this record to people}return people;}static ostream& processOS(ostream& os, vector<PersonInfo> people){for (const auto& entry : people) { // for each entry in peopleostringstream formatted, badNums; // objects created on each loopfor (const auto& nums : entry.phones) { // for each number // ``writes'' to formatted's stringformatted << " " << format(nums);}if (badNums.str().empty()) // there were no bad numbersos << entry.name << " " // print the name << formatted.str() << endl; // and reformatted numbers else // otherwise, print the name and bad numberscerr << "input error: " << entry.name<< " invalid number(s) " << badNums.str() << endl;} return os;}static void ioString4(){ vector<PersonInfo> vec = getData(cin);processOS(cout, vec); }【引用】
總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(8)chapter8 类:IO库-string流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(8)c
- 下一篇: C++ Primer 5th笔记(9)c