4

I have a very simple program, that is expected to take X characters of less from the user and print them back:

#include <stdio.h>
#define MAX_INPUT_LENGTH 8
#define HOME 1

int main()
{
    char vstup[MAX_INPUT_LENGTH];

    printf("Write something. But no more than "MAX_INPUT_LENGTH" characters.\n");
    scanf("%"MAX_INPUT_LENGTH"s", vstup);
    printf(vstup);


    system("pause");
    return 0;
}

Of course, my attempt with "blah"CONSTANT"blah" does not work. But there should be away to do it, shouldn't it? I thought constant are mostly just replaced pieces of text in the program, with only some basic logic.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • 2
    I found an answer, it just had different title than I would expect: http://stackoverflow.com/questions/5459868/c-preprocessor-concatenate-int-to-string. I wonder if I'll get helpful flag for voting to close my own question. – Tomáš Zato Apr 23 '14 at 17:22
  • http://gcc.gnu.org/onlinedocs/cpp/Stringification.html – ajay Apr 23 '14 at 17:33
  • Just in case you've wondered, there is no helpful point for flaging own questions. – Tomáš Zato Apr 23 '14 at 19:05

2 Answers2

7

This works for me.

#include <stdio.h>

#define STR2(a) #a
#define STR(a) STR2(a)

#define MAX_INPUT_LENGTH 8

int main()
{
   char vstup[MAX_INPUT_LENGTH+1];

   printf("Write something. But no more than " STR(MAX_INPUT_LENGTH) " characters.\n");
   scanf("%" STR(MAX_INPUT_LENGTH) "s", vstup);
   printf("%s\n", vstup);

   return 0;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
-1

This is my version:

int max;
char frmt[10];

memset( frmt, 0, sizeof( frmt ) );

printf( "Enter a number:" );
scanf( "%d", &max );

char vstup[max];

printf( "Write something. But no more than %d characters.\n", max );

frmt[0] = '\%';
sprintf( frmt + strlen( frmt ), "%ds", max );

scanf( frmt, vstup );
printf( vstup );
szpal
  • 647
  • 9
  • 27