0

I'm trying to pass a number to scanf of how many characters I want to read from the input stream. However, I can't get it to work.

My code works when I just put the number in the code, but I want to pass the number through #define to change it easily.

This works:

#include <stdio.h>

int main(void)
{
    char tab[11];

    printf("Podaj tekst: ");
    scanf("%10[^\n]", tab);

    printf("%s", tab);
}

This doesn't work (it only gets characters up until first whitespace character):

#include <stdio.h>

#define size 10

int main(void)
{
    char tab[size+1];

    printf("Podaj tekst: ");
    scanf("%size[^\n]", tab);

    printf("%s", tab);
}

It seems strange to me that it doesn't work. Is there any workaround to do what I want (besides using fgets)?

static_cast
  • 1,174
  • 1
  • 15
  • 21
kunek
  • 91
  • 5

1 Answers1

5

You can convert numerals or other text to strings with the preprocessor # operator. This requires using two macros, one to expand the size macro and another to apply the operator:

#define size 10

#define StringifyHelper(x)  #x
#define Stringify(x)        StringifyHelper(x)

...

char tab[size+1];
scanf("%" Stringify(size) "[^\n]", tab);
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312