meb*_*rbo 1 c string-formatting
说我想打印使用
printf(format, "YYYYMMDD");
Run Code Online (Sandbox Code Playgroud)
如果我希望我的输出看起来像"MM-DD-YYYY",格式看起来怎么样?
谢谢.
让我添加我的完整代码,这样就不会有任何混淆.
我有一个sruct定义为
typedef struct{
char *dt;
float op, hi, lo, cl, vl;
}STOCKDATA;
Run Code Online (Sandbox Code Playgroud)
然后调用一个函数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include "../include/struct.h"
#include "../include/function.h"
#include "../include/utility.h"
#define linemax 514
void stockData(char *ticker)
{
extern STOCKDATA *stockdata;
extern int nrows;
//count number of lines in file..............................
char *filename;
mkstring("../data/", ticker, filename);
nrows=linesInFile(filename);
//allocate stockdata.........................................
stockdata=malloc_stockdata(0,nrows-1);
//open file to read into stockdata...........................
FILE *fp;
fp = fopen(filename, "r");
if(fp==NULL)
{
printf("%s%s\n", "Can't open data file ", filename);
exit(1);
}
char delimiters[] = " ,";
char line[linemax];
char *tmp;
fgets(line, linemax, fp); //skip header
int count=0; //count number of lines
while( fgets(line, linemax, fp) !=NULL)
{
tmp=strtok(line, delimiters); //ticker (skipped)
stockdata[count].dt= strtok(NULL, delimiters); //date
//printf("%s\n", stockdata[count].dt);
stockdata[count].op=atof(strtok(NULL, delimiters)); //open
stockdata[count].hi=atof(strtok(NULL, delimiters)); //high
stockdata[count].lo=atof(strtok(NULL, delimiters)); //low
stockdata[count].cl=atof(strtok(NULL, delimiters)); //close
stockdata[count].vl=atof(strtok(NULL, delimiters)); //volume
count++;
}
fclose(fp);
}
Run Code Online (Sandbox Code Playgroud)
然后调用函数:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "../include/struct.h"
#include "../include/function.h"
#include "../include/utility.h"
#define cutoff 10
void writeData(char *ticker)
{
extern STOCKDATA *stockdata;
extern int nrows;
//open output file........................................
char *filename;
mkstring("../output/", ticker, filename);
FILE *fp;
fp = fopen(filename, "w");
if(fp==NULL)
{
printf("%s%s\n", "Can't open data file ", filename);
exit(1);
}
int k;
char *format="%-15s%-10.2f%-10.2f%-10.2f%-10.2f%-10.0f\n";
for (k=nrows-cutoff; k<nrows; k++)
{
fprintf(fp, format, stockdata[k].dt,
stockdata[k].op,
stockdata[k].hi,
stockdata[k].lo,
stockdata[k].cl,
stockdata[k].vl );
}
fclose(fp);
}
Run Code Online (Sandbox Code Playgroud)
现在,我在最后一个函数调用中定义'format',我试图以MM-DD-YYYY格式打印stockdata [k] .dt.数据文件中的字符串是YYYYMMDD.
你想要研究strptime和strftime.首先,您需要解析您拥有的日期(使用strptime),如下所示:
struct tm timeStruct;
strptime(dateString, "%Y%m%d", &timeStruct);
Run Code Online (Sandbox Code Playgroud)
然后使用以下命令将其转换为新格式strftime:
strftime(outputString, sizeof(outputString), "%m-%d-%Y", &timeStruct);
Run Code Online (Sandbox Code Playgroud)
现在outputString包含您想要的格式的日期.
| 归档时间: |
|
| 查看次数: |
4125 次 |
| 最近记录: |