问题描述
我有一个int变量(总是
如果myint = 1,则为
,mystr =" 01"
如果myint = 81,mystr =" 81"
目前我无法弄清楚如何干净利落地完成这项工作。
然后我希望将一堆这些字符串推入一个数组,例如:
typedef char LABEL [3];
LABEL mystrArray [100];
但是阅读了几个教程后,我仍然不清楚做字符串数组的最佳方法。在这种情况下,也没有
怎么做。
任何帮助都非常感谢!
欢呼,
Ben
对于第一个问题,google sprintf并注意
格式化说明符。那里有一些东西可以指定要输出的字符串的宽度
,以及是否用
''0'填充该宽度或者空格。
你的第二个问题,就是这样做
char mystrArray [3] [100];
一切这需要一个char *参数,你想在其上操作
mystrArray的一个元素(即sprintf:
sprintf(mystrArray [0],< extra args> )
sprintf(mystrArray [1],< extra args>)
sprintf(mystrArray [2],< extra args>)
>
使用指向char和商店的数组(静态或动态)
通过malloc''将数组的每个成员的字符串设置为所需的
大小。如果你事先知道字符串的大小,并且如果他们在执行期间不会改变
,那么静态的2d数组可能会更简单。
I have an int variable (always <100) that I want to convert to a two character string, e.g.
if myint = 1, mystr = "01"
if myint = 81, mystr = "81"
At the moment I can''t figure out how to do this cleanly.
Then I wish to push a bunch of these strings into an array, for example:
typedef char LABEL[3];
LABEL mystrArray[100];
But having read a couple of tutorials I am still no clearer on the best way to do an "array of strings" in this situation, nor
how to do it.
Any help much appreciated!
cheers,
Ben
For the first problem, google sprintf and pay attention to the
formatting specifiers. There''s something in there to specify the width
of the string to be output, and whether or not to pad that width with
''0''s or spaces.
Your second question, just do
char mystrArray[3][100];
Anything that requires an char* argument where you want to operate on
one of the elements of mystrArray (ie sprintf:
sprintf(mystrArray[0], <extra args> )
sprintf(mystrArray[1], <extra args> )
sprintf(mystrArray[2], <extra args> )
Use an array, (either static or dynamic), of pointers to char and store
the strings by malloc''ing each member of the array to the required
size. If you know the sizes of strings in advance and if they won''t
change during execution, then a static 2d array might be simpler.
这篇关于字符串,字符串和诅咒字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!