简体   繁体   中英

how to print escape character in string taken from command line argument?

After compiling the following code, I runs it like

input: ./a.out stack'\\n'overflow

output:

stack\noverflow

input: ./a.out stack"\\n"overflow

output:

stack\noverflow

input: ./a.out stack\\\\noverflow

output:

stack\noverflow  

expected output for above inputs:

stack    
overflow

Here is my code:

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("string from comand line : %s\n", argv[1]);
}

"Escape sequences" in string or characters in code is resolved by the compiler at compile-time . It's not handled at run-time at all.

If you're in a POSIX system (like macOS or Linux or similar) then you can use the shell to insert the newlines for you when running your program:

$ ./a.out '`echo -n -e "stack\noverflow"`'

That will invoke the echo command and ask it to echo the string "stack\\noverflow" without trailing newline (that's what the -n options does). The embedded "\\n" will be parsed by echo (because of the -e option) and insert a newline into the string it "prints". The output printed by echo will be passed as a single argument to your program.

The only other option is to explicitly parse the string in your program, and print a newline when it finds the character '\\\\' followed by the character 'n' .

check this program , input : stack'\\n'overflow
output : stack
overflow

#include<stdio.h>  
#include<string.h>  

void addescapeseq(char *ptr)  
{  
    char *temp;  
    while(strstr(ptr,"\\n")||strstr(ptr,"\\t")||strstr(ptr,"\\r"))  
    {  
        if(temp=strstr(ptr,"\\n"))  
        {  
            *temp=10;  
            strcpy(temp+1,temp+2);  
        }  
        else if(temp=strstr(ptr,"\\r"))  
        {  
            *temp=13;  
            strcpy(temp+1,temp+2);  
        }
        else if(temp=strstr(ptr,"\\t"))  
        {  
            *temp=9;  
            strcpy(temp+1,temp+2);  
        }  
    }  
}  

int main(int argc,char *argv[])  
{  
    addescapeseq(argv[1]);  
    printf("Data : %s\n",argv[1]);  
}  

try to work with this function :

void ft_putstr(char *s)
{
  int i = 0;

  while (s[i])
    {
      if (s[i] == '\\')
        {
          if (s[i + 1] == 'n')
            {
              putchar('\n');
              i += 2;
            }
        }
      if (s[i] != '\0')
        {
          putchar(s[i]);
          i++;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM