I have regular string literal and want to print it as it is - raw, similar how repr()
function in Python does.
For example:
char* text = "this thing\n";
printf("%s", text);
How do I get C to print
this thing\n
instead of
this thing
I have regular string literal and want to print it as it is - raw, similar how repr()
function in Python does.
For example:
char* text = "this thing\n";
printf("%s", text);
How do I get C to print
this thing\n
instead of
this thing
There are few solutions:
\n
with \
, so backslash before n
is recognized as normal symbol, and therefore n
isn't included to special symbol: printf("This thing\\n");
printf(R"(This thing\n)");
void myRepr(const char* str)
{
while (*str != '\0') {
switch (*str) {
case '\n':
fputs("\\n", stdout);
break;
case '\t':
fputs("\\t", stdout);
break;
// case ...
default:
fputc(*str, stdout);
}
++str;
}
}
Full solution:
#include <stdio.h>
int main () {
printf("This thing\\n");
return 0;
}
You can use "\\n"
to print \n u can also use it with \t
.
int main(){
char* text = "this thing\\n";
printf("%s", text);
}
or you can do it like this:
#include <stdio.h>
#include <string.h>
void newline(char* str){
int i;
for(i=0; i<strlen(str); i++){ // iterate through the string
// 10 == the ascii code for new line
if(str[i] != 10){
printf("%c", str[i]);
}
else if (str[i] == 10){
printf("\\n");
}
}
}
void newline2(char* str){ // same function useing in line if
int i;
for(i=0; i<strlen(str); i++){
str[i] != 10 ? printf("%c", str[i]) : printf("\\n");
}
}
int main(){
char* text = "this \n thing\n";
newline(text);
newline2(text);
}