Hatena::Groupcprogramming

てーげーC言語

2009-02-08

3-2

| 15:56

タブと改行を¥t, ¥nで出力

#include <stdio.h>
#define MAX_LENGTH 256

void escape(char* s, char* t); 

int main()
{
  char s[256], t[256], c;
  char* tp; 
  char* sp; 
  
  sp = s;
  tp = t;

  while ((c = getchar()) != EOF) {
    *sp++ = c;
  }   
  *sp = '\0';

  escape(s, t); 
  printf("%s\n", t);    

  return 0;
}

void escape(char* s, char* t)
{
  while(*s) {
    switch(*s) {
      case '\n':
        *t++ = '\\';
        *t++ = 'n';
        break;
      case '\t':
        *t++ = '\\';
        *t++ = 't';
        break;
      default:
        *t++ = *s; 
    }   
    s++;
  }
  *t = '\0';
}
# ./a.out                
hello   world
!
hello\tworld\n!\n

逆版

#include <stdio.h>
#define MAX_LENGTH 256

void deescape(char* s, char* t);

int main()
{
  char s[] = "hell\to world\n!";
  char t[256];
//  char c;
  char* tp; 
  char* sp; 
  
  sp = s;
  tp = t;

//  while ((c = getchar()) != EOF) {
//    *sp++ = c;
//  } 
//  *sp = '\0';

  deescape(s, t); 
  printf("%s\n", t);    

  return 0;
}

void deescape(char* s, char* t)
{
  while(*s) {
    switch(*s) {
      case '\\':
        if (*(s+1) == 'n') {
          *t++ = '\n';
          s++;
        } else if (*(s+1) == 't') {
          *t++ = '\t';
          s++;
        } else {
          *t++ = '\\';
        }
        break;
      default:
        *t++ = *s; 
    }   
    s++;
  }
  *t = '\0';
}
# ./a.out                  
hell    o world
!