使用sprintf打印字符串值 [英] Using sprintf to print string value
问题描述
实际上,我在Gnuplot中遇到了这个问题.但是以一种简单的方式,问题是我想使用sprintf以字符串格式打印,即使字符串由数字和符号组成.像这样:
Actually, I get this problem in Gnuplot. But in a simple way, the problem is I want to use sprintf to print in string format, even though the string consists of numbers and symbol. Like this:
a = '12/7'
sprintf('%.f', a)
我能够在Gnuplot中运行它,但是它只显示符号"/"之前的数字.我希望输出应打印变量a
的所有内容,即'12/7'.对这种情况有什么建议吗?
I am able to run it in Gnuplot, but it only shows numbers before symbol "/". I expect the output should print all the content of variable a
which is '12/7'. Any suggestion for this case?
推荐答案
如果要引用gnuplot
中的sprintf
内置函数,则文档help sprintf
表示:
If you are referring to the sprintf
built-in function in gnuplot
, the documentation help sprintf
says:
sprintf("format",var1,var2,...)
应用标准C语言格式 指定多个参数,并返回结果字符串.如果 您要使用gnuplot自己的格式说明符,必须改为 呼叫gprintf()
.有关sprintf格式说明符的信息, 请参阅标准的C语言文档或Unix sprintf手册 页面.
sprintf("format",var1,var2,...)
applies standard C-language format specifiers to multiple arguments and returns the resulting string. If you want to use gnuplot's own format specifiers, you must instead callgprintf()
. For information on sprintf format specifiers, please see standard C-language documentation or the unix sprintf man page.
在%f
的Unix手册页中说(被截断):
In the Unix man page for %f
says (truncated):
%f,%F-将double参数四舍五入并转换为十进制 符号 格式为[-] ddd.ddd,其中 小数点字符等于精度规格.
%f, %F -- The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification.
因此,您需要使用其他格式说明符.如fedorqui所指出,适当的格式说明符是%s
.
Hence, you need to use a different format specifier. As fedorqui pointed out the appropriate format specifier is %s
.
我经常参考此链接中的表以查找适当的格式说明符(我发现C手册页有点长).
I often refer to the table in this link for looking up the appropriate format specifiers (I find the C man page a bit long).
将sprintf
与文件中的字符串一起使用
Using sprintf
with strings from files
为了使用sprintf
格式化文件中的字符串,您需要指定文件中的列以从中提取字符串信息.这需要使用stringcolumn
命令来完成,而不仅仅是使用$
符号.
In order to use sprintf
to format a string from a file, you need to specify the column in the file to extract the string information from. This needs to be done using the stringcolumn
command instead of just using a $
sign.
例如,如果要包含文件中的数字,则可以使用以下命令:
For example, if you wanted to include a number from a file you might use a command like:
plot "data.dat" using 1:2:(sprintf('%f', $3)) with labels
但是对于字符串,您需要:
But for a string you need:
plot "data.dat" using 1:2:(sprintf('%s', stringcolumn(3))) with labels
这篇关于使用sprintf打印字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!