Printing variable in quotation marks C++ - c++

given:
string element = "hello";
I would like to have the following printed:
"hello" //with quotation marks
I found how to print words with quotation marks using \"hello\", but I would like to use my variable name element to print out "hello".

The closest you can get to have
string element = "hello";
std::cout << element
and have it print
"hello"
is to use std::quoted That would make the code
string element = "hello";
std::cout << std::quoted(element);
and it would output
"hello"
Do note that std::quoted does more then just add the out quotes. If your string contains quotes then it will modify those and add a \ in from of them. That means
string element = "hello \"there\" bob";
std::cout << std::quoted(element);
will print
"hello \"there\" bob"
instead of
"hello "there" bob"

use forward slash in front of quotation marks
std::cout << "\"" << element << "\"" << std::endl;
if you want to have quotation mark inside your string,
assign the variable with quotation mark with forward slash
string element = "\"hello\"";

You'll have to write the quotation marks and the variable extra, like
std::cout << '\"' << element << '\"';
BTW: in contrast to a string literal like "\"", where you have to escape double quotes, by using a character literal, you can get away without escaping: So the following is valid as well:
std::cout << '"' << element << '"';

string element = "\"hello\"";
std::cout << element;

Related

Why do I obtain this strange character?

Why does my C++ program create the strange character shown below in the pictures? The picture on the left with the black background is from the terminal. The picture on the right with the white background is from the output file. Before, it was a "\v" now it changes to some sort of astrological symbol or symbol to denote males. 0_o This makes no sense to me. What am I missing? How can I have my program output just a backslash v?
Please see my code below:
// SplitActivitiesFoo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string s = "foo:bar-this-is-more_text#\venus \"some more text here to read.\"";
vector<string> first_part;
fstream outfile;
outfile.open("out.foobar");
for (int i = 0; i < s.size(); ++i){
cout << "s[" << i << "]: " << s[i] << endl;
outfile << s[i] << endl;
}
return 0;
}
Also, assume that I do not want to modify my string 's' in this case. I want to be able to parse each character of the string and work around the strange character somehow.This is because in the actual program the string will be read in from a file and parsed then sent to another function. I guess I could figure out a way to programmatically add backslashes...
How can I have my program output just a backslash v?
If you want a backslash, then you need to escape it: "#\\venus".
This is required because a backslash denotes that the next character should be interpreted as something special (note that you were already using this when you wanted double-quotes). So the compiler has no way of knowing you actually wanted a backslash unless you tell it.
A literal backslash character therefore has the syntax \\. This is the case in both string literals ("\\") and character literals ('\\').
Why does my C++ program create the strange character shown below in the picture?
Your string contains the \v control character (vertical tab), and the way it's displayed is dependent on your terminal and font. It looks like your terminal is using symbols from the traditional MSDOS code page.
I found an image for you here, which shows exactly that symbol for the vertical tab (vt) entry at value 11 (0x0b):
Also, assume that I do not want to modify my string 's' in this case. I want to be able to parse each character of the string and work around the strange character somehow.
Well, I just saw you add the above part to your question. Now you're in difficult territory. Because your string literal does not actually contain the character v or any backslashes. It only appears that way in code. As already said, the compiler has interpreted those characters and substituted them for you.
If you insist on printing v instead of a vertical tab for some crazy reason that is hopefully not related to an XY Problem, then you can construct a lookup-table for every character and then replace undesirables with something else:
char lookup[256];
std::iota( lookup, lookup + 256, 0 ); // Using iota from <numeric>
lookup['\v'] = 'v';
for (int i = 0; i < s.size(); ++i)
{
cout << "s[" << i << "]: " << lookup[s[i]] << endl;
outfile << lookup[s[i]] << endl;
}
Now, this won't print the backslashes. To undo the string further check out std::iscntrl. It's locale-dependent, but you could utilise it. Or just something naive like:
const char *lookup[256] = { 0 };
s['\f'] = "\\f";
s['\n'] = "\\n";
s['\r'] = "\\r";
s['\t'] = "\\t";
s['\v'] = "\\v";
s['\"'] = "\\\"";
// Maybe add other controls such as 0x0E => "\\x0e" ...
for (int i = 0; i < s.size(); ++i)
{
const char * x = lookup[s[i]];
if( x ) {
cout << "s[" << i << "]: " << x << endl;
outfile << x << endl;
} else {
cout << "s[" << i << "]: " << s[i] << endl;
outfile << s[i] << endl;
}
}
Be aware there is no way to correctly reconstruct the escaped string as it originally appeared in code, because there are multiple ways to escape characters. Including ordinary characters.
Most likely the terminal that you are using cannot decipher the vertical space code "\v", thus printing something else. On my terminal it prints:
foo:bar-this-is-more_text#
enus "some more text here to read."
To print the "\v" change or code to:
String s = "foo:bar-this-is-more_text#\\venus \"some more text here to read.\"";
What am I missing? How can I have my program output just a backslash v?
You are escaping the letter v. To print backslash and v, escape the backslash.
That is, print double backslash and a v.
\\v

C++ Programming Principles "\n" or '\n' [duplicate]

This question already has answers here:
"\n" or '\n' or std::endl to std::cout? [duplicate]
(6 answers)
Closed 7 years ago.
Ok so I am working through examples thought the Bjarne's book. And I understand that single characters are delimited by single quotes, such as 'x'.
Then there are double quotes which delimit strings, such as "Hello,!"
In this book there are moment when this makes sense and times when they don't make sense.
For example:
cout << "Hello, " << first <<" << second << '\n'; //doesn't /n have single quotes?
cout << "Hello, " << first_name << " (age " << age << ")\n"; // why does /n have double quotes around it?
If anyone can explain the syntax differences between the two examples, that would greatly be appreciated.
EDIT-----------------------
cout << "Hello, " << first <<" << second << '\n'; //doesn't /n have single quotes?
Okay so /n is accounted for as a single character in the first example and as two in the second....... ) + /n
My follow up question is with the first example. If the single quotes delimit the /n. Why is there only 3 sets of ""s? Shouldn't it be like this:
<
The compiler recognizes the sequence \n in a character (or string) literal as a single character, a newline. That's why it can be used in single quotes as a character literal.
In the second line, the newline is inside double quotes because it's not a single character literal, it's a string containing the characters ) and \n (plus the string terminator).
The difference is, that 'x' is a char and "x" is a c-string (const char*) of length 2 (the character x and the null). In your example, this makes no difference because the ostream operator<< can handle both, char and const char*, but for c-functions like strlen, strcmp and so on, this makes a huge difference if you're passing a single char or a string with only one char in it (and the nullterminator).
\n is considered one character, even though it is two. It is short for creating a new line. You can also use the endl; command. I think it is easier and looks nicer in the code.
It is in double quotes in this situation because it is including more than one character with the ). In a normal situation the \n could be put in singles '' or doubles "".
*Note you can only use endl; if you have declared you are using namespace std;
Otherwise it is std::endl;

How to output verbatim strings in C++

Suppose I need to output some program code from my C++ code. So I need to print things like:
cout << "foo(\"hello\", \"world\", 5)" << endl;
Is there a way so that I do not need to escape each " ?
With C++11 you can do
R"delimeter(foo("hello", "world",5))delimeter"
Where R"delimeter( defines the start of a raw string, delimeter is a label up to 16 characters, and )delimeter" ends the raw string.
If you're using C++03, you can use a Macro to do what you want:
#define PRINT_STRING(s) cout << (#s) << endl;
int main() {
cout << "foo(\"hello\", \"world\", 5)" << endl;
PRINT_STRING(foo("hello", "world", 5))
return 0;
}
Returns
output:
foo("hello", "world", 5)
foo("hello", "world", 5)
You can see it here: http://ideone.com/G6TvU3
If your compiler supports C++11 the multiline quote construct is R"LABEL( Where LABEL is a valid label. To end the quote use )LABEL"

How to display "" itself as a string

Is there any way "" (double quotes itself) can be displayed as a string in c++
I tried cout << " "" "; which obviously does not work.
You need to escape them with '\' inside your string:
cout << " \"\" "
You need to escape your string.
cout << " \"\" ";
You need to escape your string, for example:
#include <iostream>
using namespace std;
int main()
{
cout << " \"\" ";
}
Output:
""
The two easiest ways I know of are as an escaped value in a string:
cout << "\"";
and as a character:
cout << '"';
I generally prefer the latter, as emacs's C++ mode colorizes it better. If you use the former, it gets confused and thinks everything after the third quote is inside a string. It is (debatably) less confusing for humans too.

boost regex sub-string match

I want to return output "match" if the pattern "regular" is a sub-string of variable st. Is this possible?
int main()
{
string st = "some regular expressions are Regxyzr";
boost::regex ex("[Rr]egular");
if (boost::regex_match(st, ex))
{
cout << "match" << endl;
}
else
{
cout << "not match" << endl;
}
}
The boost::regex_match only matches the whole string, you probably want boost::regex_search instead.
regex_search does what you want; regex_match is documented as
determines whether a given regular
expression matches all of a given
character sequence
(the emphasis is in the original URL I'm quoting from).
Your question is answered with example in library documentation - boost::regex
Alternate approach:
You can use boost::regex_iterator, this is useful for parsing file etc.
string[0],
string[1]
below indicates start and end iterator.
Ex:
boost::regex_iterator stIter(string[0], string[end], regExpression)
boost::regex_iterator endIter
for (stIter; stIter != endIter; ++stIter)
{
cout << " Whole string " << (*stIter)[0] << endl;
cout << " First sub-group " << (*stIter)[1] << endl;
}
}