0

I am learning C with Deitel's and Deitel's C programming book. Most of the times, when they use the scanf fucntion, for a char name[20];, they usually write: scanf("%19s", name);, in order to avoid buffer overflow.

But what can we do if the length of the array is a symbolic constant, say #define LENGTH 20. Obviously, using scanf("%LENGTHs, name); or even scanf("%"LENGTH"s", name); doesn't really help.

My problem also applies to the fscanf function, when we have to do with a stream different than stdin.

1
  • Use fgets() and avoid using scanf(). scanf() does input and parsing and is inadequate for both tasks. Commented May 1, 2016 at 17:11

2 Answers 2

4

Like this:

#include <stdio.h> #define STR_(x) #x #define STR(x) STR_(x) #define LENGTH 20 int main(void){ char name[LENGTH+1]; scanf("%" STR(LENGTH) "s", name); puts(name); return 0; } 

See Stringification for more information on this.

Sign up to request clarification or add additional context in comments.

Comments

3

Is better to use fgets(buffer, sizeof(buffer), stdin)

But If you want to use scanf() you can create the format at runtime or
re-define LENGTH to be a string;

#define LENGTH "20" scanf(" %" LENGTH "[^\n]", name); 

Edit:

try this:

#include <stdio.h> #define LENGTH "10" int main(void) { char name[20]; scanf(" %" LENGTH "[^\n]", name); puts(name); return 0; } 

Input: abcdefghijklmnopqrstuvxyz
Output: abcdefghij

All the best.

1 Comment

The size of the array and LENGTH are not related. So scanf(" %19[^\n]", name); is better than scanf(" %" LENGTH "[^\n]", name); in this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.