1

I'm wondering how can I get variable length word with fscanf :

I was doing something like :

char w[WORD_LENGTH_MAX + 1];
fscanf(f1, "%" XSTR(WORD_LENGTH_MAX) "s", w);

but can't use preprocessor anymore because I want WORD_LENGTH_MAX to be variable, actually coming from argv. Now I have something like this :

length = argv[0];
w[length + 1];
fscanf(f1, "%" ???length??? "s", w);

but don't know how to make this to work

Ankermann
  • 31
  • 3
  • 1
    You can build your format string using e.g.: `sprintf` – UnholySheep Jan 09 '21 at 10:22
  • 1
    Your title is a little misleading as it implies the `%[...]` format specifier, which many beginners mistakenly end with an `s`. Perhaps you should say something about "%s scanf specifier with field width from variable" or similar, if that's what you mean. – Some programmer dude Jan 09 '21 at 10:26

1 Answers1

0

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] = '\0';
chqrlie
  • 131,814
  • 10
  • 121
  • 189