std::quoted in C++ 14
Last Updated :
06 Sep, 2023
When it comes to C++ programming dealing with strings that have spaces, special characters, and formatting can be quite a hurdle. Luckily there is the std::quoted function that comes to the rescue. It provides a way to handle and manipulate the input and output of strings while preserving their formatting. In this article, we will explore the concept of std::quoted. See how it can be effectively utilized.
In versions of C++14 and, beyond the std::quoted function offers a solution, for the challenge mentioned earlier. It allows you to safely handle strings that contain spaces and special characters while keeping their formatting intact. This function is defined in the <iomanip> header. It becomes particularly handy when used alongside the std::getline function.
Syntax
The syntax for using std::quoted is as follows:
std::quoted(str)
where,
Examples of std::quoted
The following examples will help us understand the use of std::quoted in C++ programs.
Example 1:
- The code starts by including the header files using the #include directives.
- We define a variable called “input” of type std::string and initialize it with the formatted content “Hello, World!”.
- Next, we use std::cout to display the content demonstrating how it looks before applying std::quoted.
- To encapsulate the content, within quotes and protect any characters or spaces we utilize the std::quoted function and output its quoted version.
C++14
#include <iostream>
#include <iomanip>
#include <string>
int main() {
std::string input = "Hello, Geeks!" ;
std::cout << "Original content: " << input << std::endl;
std::cout << "Quoted content: " << std::quoted(input) << std::endl;
return 0;
}
|
Output
Original content: Hello, Geeks!
Quoted content: "Hello, Geeks!"
Example 2:
- Now let’s declare a variable named “Input” of type std::string to store the user’s input.
- In this example, we simulate user input by assigning a string with formatting elements to Input.
- To showcase the original input, with its intended formatting we display it as is.
- Finally using std::quoted again we output the quoted version of the user input. This ensures that any spaces or special characters are accurately preserved and displayed.
C++14
#include <iostream>
#include <iomanip>
#include <string>
int main() {
std::string Input;
Input = "Hello, Geek! Have you solved any coding problem today?" ;
std::cout << "Original Input: " << Input << std::endl;
std::cout << "Quoted Input: " << std::quoted(Input) << std::endl;
return 0;
}
|
Output
Original Input: Hello, Geek! Have you solved any coding problem today?
Quoted Input: "Hello, Geek! Have you solved any coding problem today?"
Related Article:
Share your thoughts in the comments
Please Login to comment...