我想从 txt 文件中导入一个值并在 tikz 中使用它。但由于某种原因,这不起作用(第 25 行)。我找不到像 \protect-command 这样的解决方法,它适用于 \caption 或 \section。
错误信息是:
\tikz@scan@point@coordinate 定义中的参数数量非法。
\documentclass[11pt,a4paper]{article}
%\usepackage{filecontents}
\begin{filecontents*}{text1.txt}
per = 10
\end{filecontents*}
\usepackage{tikz}
\usepackage{datatool}
\DTLsetseparator{ = }
\DTLloaddb[noheader, keys={thekey,thevalue}]{para}{text1.txt}
% Loads mydata.dat with column headers 'thekey' and 'thevalue'
\newcommand{\datapar}[1]{\DTLfetch{para}{thekey}{#1}{thevalue}}
\newcommand{\test}{10} % alternative implementation (for testing)
\begin{document}
insert value form text1.txt: \datapar{per}
\begin{figure}[!ht]
\begin{center}
\begin{tikzpicture}
\draw (\datapar{per},0) -- (4,0); %value from text1.txt in tikz (not working)
\draw (\test,0) -- (4,0); % same value from different variable is no problem.
\end{tikzpicture}
\caption{caption is working, too: \protect\datapar{per}}
\end{center}
\end{figure}
\end{document}
答案1
问题是\DTLfetch
检索并打印值。但您不想打印它,而是想将其用于计算。使用 pgf 您不需要创建可扩展的变体,只需声明一个检索值并将其存储到的函数即可。\pgfmathresult
我调用该函数datapar
以匹配您的宏的名称,但显然您可以创建这种类型的更复杂的函数。
\documentclass[11pt,a4paper]{article}
\begin{filecontents*}[overwrite]{text1.txt}
per = 10
\end{filecontents*}
\usepackage{tikz}
\usepackage{datatool}
\DTLsetseparator{ = }
\DTLloaddb[noheader, keys={thekey,thevalue}]{para}{text1.txt}
% Loads mydata.dat with column headers 'thekey' and 'thevalue'
\newcommand{\datapar}[1]{\DTLfetch{para}{thekey}{#1}{thevalue}}
\pgfmathdeclarefunction{datapar}{1}{%
\edtlgetrowforvalue{para}{\dtlcolumnindex{para}{thekey}}{#1}%
\dtlgetentryfromcurrentrow{\pgfmathresult}{\dtlcolumnindex{para}{thevalue}}%
}
\newcommand{\test}{10} % alternative implementation (for testing)
%\show\DTLfetch
\begin{document}
insert value form text1.txt: \datapar{per}
\begin{figure}[!ht]
\begin{center}
\begin{tikzpicture}
\draw ({datapar("per")},0) -- (4,0); %value from text1.txt in tikz (not working)
\draw[red,dashed] (\test,0) -- (4,0); % same value from different variable is no problem.
\end{tikzpicture}
\caption{caption is working, too: \protect\datapar{per}}
\end{center}
\end{figure}
\end{document}
我添加了第二条线(红色虚线),以便确认两条线具有相同的起点和终点。