Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create char from char* that includes escape character

Tags:

c

char

pointers

Consider the following char* example:

char* s = "\n";

How can this be converted into a single char that represents the new line character like so:

char c = '\n';

In addition to processing newlines I also need to be able to convert any character with an escape character preceeding it into a char. How is this possible?

like image 205
AgileVortex Avatar asked May 12 '11 18:05

AgileVortex


People also ask

How do I add an escape character to a string?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

What is the combination of an escape character with another character?

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences.

How do you escape special characters?

Special characters can serve different functions in the query syntax. To search for a special character that has a special function in the query syntax, you must escape the special character by adding a backslash before it, for example: To search for the string "where?", escape the question mark as follows: "where\?"

How do you escape a character in C++?

Use escape sequences only in character constants or in string literals. An error message is issued if an escape sequence is not recognized. In string and character sequences, when you want the backslash to represent itself (rather than the beginning of an escape sequence), you must use a \\ backslash escape sequence.


4 Answers

char c = *s; works.

The '\n' inside the string is only two characters in source form: after compiling it is a single character; the same for all other escape character.

The string "fo\111\tar", after compiling, has 7 characters (the 6 visible in the source code ('f', 'o', '\111', '\t', 'a', and 'r') and a null terminator).

like image 133
pmg Avatar answered Nov 03 '22 00:11

pmg


Dereference it:

char* s = "\n";
char c = *s;
like image 36
JonH Avatar answered Nov 03 '22 00:11

JonH


Do you mean something like that?

char * s = "\n";
char c = *s;
like image 40
Heisenbug Avatar answered Nov 03 '22 00:11

Heisenbug


As others said, the newline is actually only one character in memory. To get a single character from a string pointer, you can access your pointer as if it is an array (assuming, of course, that there is memory allocated for the string pointed to):

char* s = "\n";
char  c = s[0];
like image 23
GreenMatt Avatar answered Nov 03 '22 00:11

GreenMatt