次のようなことを試してください:
using namespace std;
string PeekString(stringstream& ss, int position = 0, char delim = '\n', int count = 0)
{
string returnStr = "";
int originalPos = (position > 0) ? position : ss.tellg();
if (originalPos == position) ss.seekg(position);
int pos = originalPos;
int i = 0, end = (count < 1) ? ss.str().length() : count;
char c = ss.peek();
while (c != delim && !ss.eof() && i != end)
{
returnStr += c;
pos++;
i++;
ss.seekg(pos);
c = ss.peek();
}
ss.seekg(0);
return returnStr;
}
使用法は次のようになります。
int main()
{
string s = "Hello my name is Bob1234 68foo87p\n";
stringstream ss;
ss << s;
cout << "Position 0, delim \'\\n\': " << PeekString(ss) << endl;
cout << "Position 0, delim \' \': " << PeekString(ss,0,' ') << endl;
cout << "Position 17, delim \' \': " << PeekString(ss,17,' ') << endl;
cout << "Position 25, delim \'\\n\': " << PeekString(ss, 25) << endl;
cout << "Position 27, count 3: " << PeekString(ss, 27, '\n', 3) << endl << endl;
string newstring;
char temp[100];
ss.getline(temp, 100);
newstring = temp;
cout << "What's left in the stream: " << newstring;
cin.get();
return 0;
}
出力は次のようになります。