Using sprintf to print string value

时间秒杀一切 提交于 2019-12-21 04:57:07

问题


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)

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?


回答1:


If you are referring to the sprintf built-in function in gnuplot, the documentation help sprintf says:

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 call gprintf(). For information on sprintf format specifiers, please see standard C-language documentation or the unix sprintf man page.

In the Unix man page for %f says (truncated):

%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.

Hence, you need to use a different format specifier. As fedorqui pointed out the appropriate format specifier is %s.

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).

Using sprintf with strings from files

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



回答2:


When you say

$ awk 'BEGIN {a="12/7"; printf "%.f", a}'
12

You get the int part of the number, because by using a f flag in printf you are casting it to a number instead of a string. So it is equivalent to saying:

awk 'BEGIN {a="12/7"; a=int(a); print a}'

If you want to keep all of it, use %s for string:

$ awk 'BEGIN {printf "%s", "234-456"}'
234-456


来源:https://stackoverflow.com/questions/34514279/using-sprintf-to-print-string-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!