这是我现在的代码:
srand(time(NULL));
int photo = rand()%((3+1)-1) + 1;
fp_r = fopen("ascii_art/Animals/${photo}", "r");
我想做 ('outcome/4star/${random}.jpg') 但只是用 C 语言。我能做什么?
我可能会这样做:
int main(void) {
srand(time(NULL));
char path[] = "ascii_art/Animals/?.jpg";
path[strlen(path)-5] = '0' + rand() % 3 + 1;
fp_r = fopen(path, "r);
}
更通用的方法是按照@tshiono的建议使用
sprintf()
,棘手的部分是确保模板字符串足够长,即strlen(template) + int(log10(INT_MAX) + 1) + 1
。