想到3种实现方法
// APPROACH 1:peek()
#include<iostream>
#include<sstream>
int main()
{
using namespace std;
istringstream s1("Hello world!$");
string str = s1.str();
cout << "Here is a string: " << str << "\n";
char ch;
int ct = 0;
// whether extrac the charater is determined it's $ or not, telling by peek()
cout << "\nFollowing characters are read: \n";
while (s1.peek() != '$')// peek the character, if not $, extrac it
{
s1.get(ch);
ct++;
cout << ch << " ";
}
cout << "\n(Total characters read before delimiter '$': " << ct << " )";
cout << "\n\nThe first character left in stream now is: ";
cout.put(s1.peek());
cin.get();
return 0;
}
/*
// APPROACH 2:get() and unget()
#include<iostream>
#include<sstream>
int main()
{
using namespace std;
istringstream s1("Hello world!$");
string str = s1.str();
cout << "Here is a string: " << str << "\n";
char ch;
int ct = 0;
// whether extrac the charater is determined it's $ or not, telling by peek()
cout << "\nFollowing characters are read: \n";
while (s1.get(ch) && ch != '$')
{
ct++;
cout << ch << " ";
}
s1.unget();// make the most recently extracted character '$' available again
cout << "\n(Total characters read before delimiter '$': " << ct << " )";
cout << "\n\nThe first character left in stream now is: ";
cout.put(s1.peek());
cin.get();
return 0;
}
*/
/*
// APPROACH 3: basic_istream& get( char_type* s, std::streamsize count, char_type delim );
#include<iostream>
#include<sstream>
int main()
{
using namespace std;
istringstream s1("Hello world!$");
string str = s1.str();
cout << "Here is a string: " << str << "\n";
char* ps = new char[str.size()];// store characters will be extracted by get(). +1 is for ending null
s1.get(ps, str.size(), '$');// get() will keep $ in input stream. But getline() will discard
// or s1.get(ps,ct)
ps[s1.gcount()] = '\n';// set ending null
cout << "\nFollowing characters are read: \n";
for (int i = 0; ps[i]!='\n'; i++)// or i<s1.gcount()
cout << ps[i] << " ";
cout << "\n(Total characters read before delimiter '$': " << s1.gcount() << " )";// or ct instead s1.gcount()
cout << "\n\nThe first character left in stream now is: ";
cout.put(s1.peek());
delete ps;
cin.get();
return 0;
}
*/