#include <cassert> #include <iostream> #include <sstream> int main() { std::stringstream str_stream; int onechar; // note: char cannot represent EOF std::cout << "Enter some text: "; while ( ( onechar = std::cin.get() ) != EOF ) { // exit from the loop as soon as user hits enter: if ( onechar == '\n' ) break; // Annotate individual characters: if ( isalpha( onechar ) ) { str_stream << "L-"; } else if ( isdigit( onechar ) ) { str_stream << "D-"; } else { // other choices could be // isalnum(), ispunct(), isspace() islower, isupper() str_stream << "?-"; } str_stream << char( onechar ) << '-' << onechar << '\n' ; } std::cout << str_stream.str() // str() returns std::string << std::endl ; // create a string from the stringstream: std::string result = str_stream.str(); assert( result == str_stream.str() ); // str( "" ) clears the stringstream buffer in case // if you need to use it again: str_stream.str( "" ); result = str_stream.str(); assert( result.empty() ); return 0; } /* Sample run: Enter some text: a1,B2 L-a-97 D-1-49 ?-,-44 L-B-66 D-2-50 */