Here is a short version which works using scanf
:
#include <stdio.h>
int main(void) {
char buffer[20 + 1] ; // 20 characters + 1 for '\0'
int nread ;
nread = scanf("%20[^\n]", buffer) ; // Read at most 20 characters
printf("%s\n", buffer);
return 0;
}
scanf
will automatically add the '\0'
character at the right place in buffer
and with the "%20[^\n]"
it will read at most 20 characters different from '\n'
.
If you want to put this in a function and avoid repeating 20
(error prone):
#include <stdio.h>
int read_chars (char buffer[], int len) {
char format[50] ;
sprintf(format, "%%%d[^\n]", len);
return scanf(format, buffer) ;
}
#define MAX_CHARS 20
int main(void) {
char buffer[MAX_CHARS + 1] ; // 20 characters + 1 for '\0'
read_chars (buffer, MAX_CHARS) ;
printf("%s\n", buffer);
return 0;
}
Edit: If you don't want to use sprintf
to create the format string, you could use preprocessor (will not work if MAX_CHARS
is not a preprocessor constant):
#include <stdio.h>
#define _READ_CHARS(buffer, N) scanf("%" #N "[^\n]", buffer)
#define READ_CHARS(buffer, N) _READ_CHARS(buffer, N)
#define MAX_CHARS 20
int main(void) {
char buffer[MAX_CHARS + 1] ; // 20 characters + 1 for '\0'
READ_CHARS (buffer, MAX_CHARS) ;
printf("%s\n", buffer);
return 0;
}