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?
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.
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.
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\?"
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.
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).
Dereference it:
char* s = "\n";
char c = *s;
Do you mean something like that?
char * s = "\n";
char c = *s;
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With