Can I concatenate a numeric constant with a string in C?

I have a very simple program that is expected to take X characters less from the user and return 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 this should not be, right? I thought that the constant is basically just replaced by fragments of text in the program, and only with some basic logic.

+4
source share
2 answers

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;
}
+6
source

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 );
-1
source

Source: https://habr.com/ru/post/1537760/


All Articles