Check if character equals \ in C++ - c++

I'm trying to see if a character c equals \
if (c == '\')
//do something
I don't know exactly how this is called but everything after \ turns in a character string.

Backslash is used as the escape character in C++, as it is in many other languages. If you want a literal backslash, you need to use \\:
if (c == '\\') {
}

\ backslash is an escape character.
Escape sequences are used to represent certain special characters
within string literals and character literals.
Read here
So you should do:
if (c == '\\'){
}

You need escape sequences:
\\ backslash byte 0x5c in ASCII encoding
Change the code to
if (c == '\\')

Related

How to see backslashes in string

For a function I am making, I take a string in as a parameter and do things with it. However I treat characters in the string specially if there is a backslash before it. However I am having problems even seeing the blackslash!
std::string s = "01234\6";
std::cout << s << std::endl;
std::cout << s.at(5) << std::endl;
if(s.at(5)== '\\')
std::cout << "It's a backslash" << std::endl;
else
std::cout << "It's not a backslash" << std::endl;
outputs
01234
It's not a backslash
How am I supposed to check if mystring.at(i) == '\\' if it isn't showing up at all?
The input will be coming from another file (which I can't modify) like
myfunc("% \% %");
If I read the string I count 3 '%' characters (so its not ignored by the backslash), and 0 '\' characters
edit: Code how I count
char percent = '%';
int current_index = 0;
int percent_count = 0;
int ret = str.find(percent, current_index);
while(ret != std::string::npos)
{
percent_count++;
current_index = ret +1;
ret = str.find(percent, current_index);
}
return percent_count;
C++ supports three kinds of escape sequences:
simple-escape-sequence. It is one of:
\’ \" \? \\
\a \b \f \n \r \t \v
octal-escape-sequence. It is one of:
\ octal-digit
\ octal-digit octal-digit
\ octal-digit octal-digit octal-digit
\0 is the most well known octal escape sequence that represents the null character.
hexadecimal-escape-sequence. It is one of:
\x hexadecimal-digit
hexadecimal-escape-sequence hexadecimal-digit
When you use:
std::string s = "01234\6";
the \6 part represents an octal escape sequence. It does not represent two characters.
It is the same as
std::string s = "01234?";
where ? is the character represented by the octal number 6.
In order to have \ as an element of the string, you'll need to use:
std::string s = "01234\\6";
The checking method is right, but \ escape 6, so \6 is counted once, you can check sizeof("12345\6"), which 7, or strlen("12345\6"), which is 6.
Change "12345\6" to "12345\\6".
The C++ compiler would have already treated it specially if you have backslash in the string:
std::string s = "01234\6"; //\6 is treated differently already, as unicode character \6, not as backslash + 6
Unless what you mean is you want to have a text with backslash (say, from I/O). In that case, you should put \\ to make your compiler understand that you mean it as real backslash not a unicode character:
std::string s = "01234\\6"; //double backslash here
Then you can test your program.
No compiler C++ will interpret \ as a backslash, since its the escape character. You will have to use \\ to denote a backslash in a string.

Is there a way to put quotes in a cout? [duplicate]

This question already has answers here:
Rules for C++ string literals escape character
(6 answers)
Closed 7 years ago.
I was trying to make a simple calculator and I would like to display quotes in the instruction when you first run the program.
Use \". Also known as escape sequences.
Another solution is to use raw strings:
#include <string>
#include <iostream>
int main()
{
std::cout << R"_(A raw string with " inside (and \ as well))_" << std::endl;
return 0;
}
Live example
Output:
A raw string with " inside (and \ as well)
Quotes from the Standard:
According to the Standard 2.14.5 [lex.string]:
string-literal:
encoding-prefixopt "s-char-sequenceopt"
encoding-prefixopt R raw-string
encoding-prefix:
u8
u
U
L
s-char-sequence:
s-char
s-char-sequence s-char
s-char:
any member of the source character set except
the double-quote ", backslash \, or new-line character
escape-sequence
universal-character-name
raw-string:
" d-char-sequenceopt ( r-char-sequenceopt) d-char-sequenceopt "
r-char-sequence:
r-char
r-char-sequence r-char
r-char:
any member of the source character set, except
a right parenthesis ) followed by the initial d-char-sequence
(which may be empty) followed by a double quote ".
d-char-sequence:
d-char
d-char-sequence d-char
d-char:
any member of the basic source character set except:
space, the left parenthesis (, the right parenthesis ), the backslash \,
and the control characters representing horizontal tab,
vertical tab, form feed, and newline.
A string literal is a sequence of characters (as defined in 2.14.3) surrounded by double quotes, optionally prefixed by R, u8, u8R,
u, uR, U, UR, L, or LR, as in "...", R"(...)",
u8"...", u8R"**(...)**", u"...", uR"*˜(...)*˜", U"...",
UR"zzz(...)zzz", L"...", or LR"(...)", respectively.
A string literal that has an R in the prefix is a raw string literal. The d-char-sequence serves as a delimiter. The terminating
d-char-sequence of a raw-string is the same sequence of characters
as the initial d-char-sequence. A d-char-sequence shall consist of
at most 16 characters.
[Note: The characters ( and ) are permitted in a raw-string. Thus, R"delimiter((a|b))delimiter" is equivalent to "(a|b)". —end
note ]
[Note: A source-file new-line in a raw string literal results in a new-line in the resulting execution string-literal. Assuming no
whitespace at the beginning of lines in the following example, the
assert will succeed:
const char *p = R"(a\
b
c)";
assert(std::strcmp(p, "a\\\nb\nc") == 0);
— end note ]
[Example: The raw string
R"a(
)\
a"
)a"
is equivalent to "\n)\\\na\"\n". The raw string
R"(??)"
is equivalent to "\?\?". The raw string
R"#(
)??="
)#"
is equivalent to "\n)\?\?=\"\n". —end example ]

Is it possible to return "weird" characters in a char?

I would like to know is it possbile to return "weird" characters, or rather ones that are important to the language
For example: \ ; '
I would like to know that because I need to return them by one function that's checking the unicode value of the text key, and is returning the character by it's number, I need these too.
I get a 356|error: missing terminating ' character
Line 356 looks as following
return '\';
Ideas?
The backslash is an escape for special characters. If you want a literal backslash you have to escape it with another backslash. Try:
return '\\';
The only problem here is that a backslash is used to escape characters in a literal. For example \n is a new line, \t is a horizontal tab. In your case, the compiler is seeing \' and thinking you mean a ' character (this is so you could have the ' character like so: '\''). You just need to escape your backslash:
return '\\';
Despite this looking like a character literal with two characters in it, it's not. \\ is an escape sequence which represents a single backslash.
Similarly, to return a ', you would do:
return '\'';
The list of available escape sequences are given by Table 7:
You can have a character literal containing any character from the execution character set and the resulting char will have the value of that character. However, if the value does not fit in a char, it will have implementation-defined value.
Any character can be returned.
Yet for some of them, you have to escape it using backslash: \.
So for returning backslash, you have to return:
return '\\';
To get a plain backslash use '\\'.
In C the following characters are represented using a backslash:
\a or \A : A bell
\b or \B : A backspace
\f or \F : A formfeed
\n or \N : A new line
\r or \R : A carriage return
\t or \T : A horizontal tab
\v or \V : A vertical tab
\xhh or \Xhh : A hexadecimal bit pattern
\ooo : An octal bit pattern
\0 : A null character
\" : The " character
\' : The ' character
\\ : A backslash (\)
A plain backslash confuses the system because it expects a character to follow it. Thus, you need to "escape" it. The octal/hexadecimal bit patterns may not seem too useful at first, but they let you use ANSI escape codes.
If the character following the backslash does not specify a legal escape sequence, as shown above, the result is implementation defined, but often the character following the backslash is taken literally, as though the escape were not present.
If you have to return such characters(",',\,{,]...etc) more then once, you should write a function that escapes that characters. I wrote that function once and it is:
function EscapeSpecialChars (_data) {
try {
if (!GUI_HELPER.NOU(_data)) {
return _data;
}
if (typeof (_data) != typeof (Array)) {
return _data;
}
while (_data.indexOf("
") > 0) {
_data = _data.replace("
", "");
}
while (_data.indexOf("\n") > 0) {
_data = _data.replace("\n", "\\n");
}
while (_data.indexOf("\r") > 0) {
_data = _data.replace("\r", "\\r");
}
while (_data.indexOf("\t") > 0) {
_data = _data.replace("\t", "\\t");
}
while (_data.indexOf("\b") > 0) {
_data = _data.replace("\b", "\\b");
}
while (_data.indexOf("\f") > 0) {
_data = _data.replace("\f", "\\f");
}
return _data;
} catch (err) {
alert(err);
}
},
then use it like this:
return EscapeSpecialChars("\'"{[}]");
You should improve the function. It was working for me, but it is not escaping all special characters.

How do I add a backslash after every character in a string?

I need to transform a literal filepath (C:/example.txt) to one that is compatible with the various WinAPI Registry functions (C://example.txt) and I have no idea on how to go about doing it.
I've broken it down to having to add a backslash after a certain character (/ in this case) but i'm completely stuck after that.
Guidance and Code Examples will be greatly appreciated.
I'm using C++ and VS2012.
In C++, strings are made up of individual characters, like "foo". Strings can be composed of printable characters, such as the letters of the alphabet, or non-printable characters, such as the enter key or other control characters.
You cannot type one of these non-printable characters in the normal way when populating a string. For example, if you want a string that contains "foo" then a tab, and then "bar", you can't create this by typing:
fooTABbar
because this will simply insert that many spaces -- it won't actually insert the TAB character.
You can specify these non-printable characters by "escaping" them out. This is done by inserting a back slash character (\) followed by the character's code. In the case of the string above TAB is represented by the escape sequence \t, so you would write: "foo\tbar".
The character \ is not itself a non-printable character, but C++ (and C) recognize it to be special -- it always denotes the beginning of an escape sequence. To include the character "\" in a string, it has to itself be escaped, with \\.
So in C++ if you want a string that contains:
c:\windows\foo\bar
You code this using escape sequences:
string s = "c:\\windows\\foo\\bar"
\\ is not two chars, is one char:
for(size_t i = 0, sz = sPath.size() ; i < sz ; i++)
if(sPath[i]=='/') sPath[i] = '\\';
But be aware that some APIs work with \ and some with /, so you need to check in which cases to use this replacement.
If replacing every occurrence of a forward slash with two backslashes is really what you want, then this should do the job:
size_t i = str.find('/');
while (i != string::npos)
{
string part1 = str.substr(0, i);
string part2 = str.substr(i + 1);
str = part1 + R"(\\)" + part2; // Use "\\\\" instead of R"(\\)" if your compiler doesn't support C++11's raw string literals
i = str.find('/', i + 1);
}
EDIT:
P.S. If I misunderstood the question and your intention is actually to replace every occurrence of a forward slash with just one backslash, then there is a simpler and more efficient solution (as #RemyLebeau points out in a comment):
size_t i = str.find('/');
while (i != string::npos)
{
str[i] = '\\';
i = str.find('/', i + 1);
}
Or, even better:
std::replace_if(str.begin(), str.end(), [] (char c) { return (c == '/'); }, '\\');

parsing user string, escape characters

How can I parse a string and replace all occurences of a \. with something? Yet at the same time replace all \\ with \ (literal).. Examples:
hello \. world => hello "." world
hello \\. world=> hello \. world
hello \\\. world => hello \"." world
The first reaction was to use std::replace_if, as in the following:
bool escape(false);
std::replace_if(str.begin(), str.end(), [&] (char c) {
if (c == '\\') {
escape = !escape;
} else if (escape && c == '.') {
return true;
}
return false;
},"\".\"");
However that simply changes \. by \"." sequences. Also it won't be working for \\ parts in the staring.
Is there an elegant approach to this? Before I start doing a hack job with a for loop & rebuilding the string?
Elegant approach: a finite state machine with three states:
looking for '\' (iterating through string)
found '\' and next character is '.'
found '\' and next character is '\'
To implement you could use the iterators in the default string library and the replace method.
http://www.cplusplus.com/reference/string/string/replace/