std::quoted in C++
Programming in C++ can present challenges when handling strings containing spaces, special characters, and formatting. Fortunately, the std::quoted function steps in to save the day. It offers a method for managing and working with string input and output while keeping formatting intact. In this article, we will discuss the concept of std::quoted function with its syntax, parameters, and examples.
In C++, the std::quoted function lets us to handle strings with spaces and other special characters without risk, all the while maintaining formatting consistency. This function is defined in the #include
Syntax:
Using std::quoted has the following syntax:
std::quoted(str);
In this syntax, str is the input string.
Example 1:
Let us take an example to illustrate the std::quote function in C++.
#include#include #include int main() { // define a string variable with formatted content std::string input = "Hello, JavaTPoint"; // Prints the original content std::cout << "Real content: " << input << std::endl; // Print the quoted content using std::quoted std::cout << "Quoted line: " << std::quoted(input) << std::endl; return 0; }
Output:
Real content: Hello, JavaTPoint! Quoted line: "Hello, JavaTPoint!"
Explanation:
- Using the #include directives, the code first includes the header files.
- After defining it, we initialize a variable named "input" of type std::string with the formatted text "Hello, World!".
- Before using std::quoted, we first show the content's appearance using std::cout.
- After that, we use the std::quoted function to produce the content's quoted version while enclosing it in quotes and protecting any characters or spaces.
Example 2:
Let us take another example to illustrate the std::quote function in C++.
#include#include #include int main() { std::string Input; // Enter user input Input = "Hello, JavaTpoint! Welcome to the JavaTpoint"; // Print original user input std::cout << "Real Input: " << Input << std::endl; // Print quoted user input std::cout << "Quoted Input: " << std::quoted(Input) << std::endl; return 0; }
Output:
Real Input: Hello, JavaTpoint! Welcome to the JavaTpoint Quoted Input: "Hello, JavaTpoint! Welcome to the JavaTpoint"
Explanation:
- Let's declare a variable called "Input" of type std::string to store the user's input.
- By giving Input a string that contains formatting components, we may emulate user input in this example.
- After that, we present the original input exactly how it was meant to be formatted to highlight it.
- Lastly, we output the user input that has been quoted by using std::quoted once again. It guarantees that special characters and spaces are appropriately shown and maintained.