本文介绍了C:使用 printf 等精度说明符分配字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用精度说明符(如 printf 使用)而不使用大量 for 循环来分配字符串变量.代码以 YYYYMMDD 的形式从命令行传入一个日期.要以 MM/DD/YYYY 格式打印日期,我会执行以下操作:

I want to assign a string variable using precision specifiers like printf uses and without using a ton of for loops. The code is passed in a date from the command line in the form of YYYYMMDD. To print the date in MM/DD/YYYY format, I would do the following:

char *date = argv[2];
printf("%.2s/%.2s/%.4s", &date[4], &date[6], date);

所以从命令行传递 '20130725' 将打印 '07/25/2013'

so passing '20130725' from command line will print '07/25/2013'

但是,如果我尝试,这不起作用:

However, this does not work if I try:

char *formatted_date = ("%.2s/%.2s/%.4s", &date[4], &date[6], date);
printf("%s\n", formatted_date);

从命令行传递20130725"将打印回20130725".

Passing '20130725' from command line will print '20130725' back.

我将如何以与此类似的方式分配变量,或者这在 C 中是不可能的?

How would I assign a variable in a way similar to this, or is this not possible in C?

推荐答案

初始化时不能做,但可以用sprintf(3):

You can't do it at initialization time, but you can use sprintf(3):

char formatted_date[11]; // MM/DD/YYYY plus a null terminator
sprintf(formatted_date, "%.2s/%.2s/%.4s", &date[4], &date[6], date);
printf("%s\n", formatted_date);

这篇关于C:使用 printf 等精度说明符分配字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 20:45