C++ Programming Code Examples
Learn C++ Language
str() Function in C++ Programming Language
str() Function in C++
The stringstream, ostringstream, and istringstream objects are used for input and output to a string. They behave in a manner similar to fstream, ofstream and ifstream objects. The function str() can be used in two ways. First, it can be used to get a copy of the string that is being manipulated by the current stream string. This is most useful with output strings.
The first form (1) returns a string object with a copy of the current contents of the stream.
The second form (2) sets s as the contents of the stream, discarding any previous contents. The object preserves its open mode: if this includes ios_base::ate, the writing position is moved to the end of the new sequence.
Internally, the function calls the str member of its internal string buffer object.
Syntax for str() Function in C++
//form1
string str() const;
//form2
void str (const string& s);
str
A string object, whose content is copied.
For (1), function returns a string object with a copy of the current contents in the stream buffer.
Data races
Accesses (1) or modifies (2) the ostringstream object. Concurrent access to the same object may cause data races.
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state.
/* get and set string object whose content is present in the stream by str() function code example. */
#include <sstream>
#include <iostream>
int main()
{
int n;
std::istringstream in; // could also use in("1 2")
in.str("1 2");
in >> n;
std::cout << "after reading the first int from \"1 2\", the int is "
<< n << ", str() = \"" << in.str() << "\"\n";
std::ostringstream out("1 2");
out << 3;
std::cout << "after writing the int '3' to output stream \"1 2\""
<< ", str() = \"" << out.str() << "\"\n";
std::ostringstream ate("1 2", std::ios_base::ate);
ate << 3;
std::cout << "after writing the int '3' to append stream \"1 2\""
<< ", str() = \"" << ate.str() << "\"\n";
}
To 'reverse a string' in C++ programming, ask to the user to 'enter a string', make a variable say temp of char type "start Swapping". Place First Character of the String in temp and Last
Takes input a Character and Check it whether a 'character' is capital letter, small letter, Digit or Special character. 'All characters' like small or capital letters, digits and special characters