写入外部文件时出现特殊字符的问题

写入外部文件时出现特殊字符的问题

以下 MWE 抛出错误

未定义控制序列。使用 \unhbox \voidb @x \bgroup \let \unhbox \voidb @x \setbo... l.1 ...e\egroup \spacefactor \accent@spacefactor } 进行测试?

我怎样才能编写不包含特殊字符的扩展字符串?

% ----------------------------------------------------------------------------
% "THE BEER-WARE LICENSE" (Revision 42):
% Jonathan P. Spratte  wrote this code.  As long as you retain this notice you
% can do whatever you want with this stuff. If we meet some day, and you think
% this stuff is worth it, you can buy me a beer in return. Jonathan P. Spratte
% ----------------------------------------------------------------------------

\documentclass{article}

\usepackage[utf8]{inputenc}

\makeatletter
\newwrite \fich@sol
\def\nameFile{example.sol}
\AtBeginDocument{ \immediate\openout \fich@sol \nameFile}
\makeatother


\begin{document}

\section{Test with é}

\makeatletter
\immediate\write\fich@sol{\noexpand\section{Test with é}} 
% same error with \immediate\write\fich@sol{\string\section{Test with é}}
\immediate\closeout \fich@sol
\makeatother

\input{example.sol}

\end{document}

答案1

就像@PhelypeOleinik 所说的那样,可以在这里工作,我们可以用(模数的一些其他功能)\protected@write复制它:\immediate\protected@write

\documentclass{article}

\makeatletter

\newwrite \fich@sol
\def\nameFile{example.sol}
\AtBeginDocument{ \immediate\openout \fich@sol \nameFile}
\AtEndDocument{ \immediate\closeout \fich@sol}

\newcommand\immediateprotectedwrite[2]
  {%
    \begingroup
      \let\thepage\relax
      \let\protect\@unexpandable@protect
      \edef\reserved@a{\immediate\write#1{#2}}%
      \reserved@a
    \endgroup
  }

\begin{document}

Test
\immediateprotectedwrite\fich@sol{\protect\section{Test è}}

\makeatother

\end{document}

相关内容