我对C ++很安静,我需要从MSVC ++文本字段读取输入并将其写入文件。我需要将\n
写为文件的新行,而不是\n
。
经过一番研究后,我发现转义字符只能在编译时运行。我是否可以在运行时使用它。我只使用C ++来完成这项任务。
答案 0 :(得分:2)
如果我今天在C ++中这样做,我可能会写一点不同(我在大约20年前写过这篇文章),但它至少可以提供一些灵感:
/*
** Public Domain by Jerry Coffin.
**
** Interprets a string in a manner similar to that the compiler
** does string literals in a program. All escape sequences are
** longer than their translated equivalant, so the string is
** translated in place and either remains the same length or
** becomes shorter.
*/
#include <string.h>
#include <stdio.h>
#include "snip_str.h"
char *translate(char *string)
{
char *here=string;
size_t len=strlen(string);
int num;
int numlen;
while (NULL!=(here=strchr(here,'\\')))
{
numlen=1;
switch (here[1])
{
case '\\':
break;
case 'r':
*here = '\r';
break;
case 'n':
*here = '\n';
break;
case 't':
*here = '\t';
break;
case 'v':
*here = '\v';
break;
case 'a':
*here = '\a';
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
numlen = sscanf(here,"%o",&num);
*here = (char)num;
break;
case 'x':
numlen = sscanf(here,"%x",&num);
*here = (char) num;
break;
}
num = here - string + numlen;
here++;
memmove(here,here+numlen,len-num );
}
return string;
}