You can construct the format string with snprintf
:
int length = atoi(argv[0]);
w[length + 1];
char fmt[20];
snprintf(fmt, sizeof fmt, "%%%ds", length);
fscanf(f1, fmt, w);
Yet a simpler solution is to use a while
loop:
int length = atoi(argv[0]);
w[length + 1];
int c, i = 0;
while (i <= length && (c = getchar()) != EOF) {
if (isspace(c)) {
ungetc(c, stdin);
break;
}
w[i++] = c;
}
w[i] = '';
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…