Reputation: 83
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?
Upvotes: 7
Views: 553
Reputation: 18570
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];
Upvotes: 2
Reputation: 108978
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).
Upvotes: 9