Blecccch!
Anduril's previous post noted in passing an approach to that (which I extract here, with lots of snipping before and after the relevant bit).
Not the bit after the words "or by".
I'd still prefer a fgets() and scan the string approach.
Blecccch!
Anduril's previous post noted in passing an approach to that (which I extract here, with lots of snipping before and after the relevant bit).
Not the bit after the words "or by".
I'd still prefer a fgets() and scan the string approach.
It would usually be done something like this.
Code:#include <stdio.h> #define NAME_LEN 10 /* small value for testing */ #define STR2(n) #n /* stringize */ #define STR(n) STR2(n) /* expand n */ int main(void) { char name[NAME_LEN]; scanf("%" STR(NAME_LEN-1) "[^\n]", name); printf("<%s>\n", name); return 0; }
The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss
What it really boils down to is: how can you reduce the work required to make a simple change like changing the size of a string. Think not just of changing the value of the macro, but if you change the macro used in the definition:
Using the sizeof operator is the only easy way to do this. If you can't use the sizeof operator here, you are at a disadvantage when it comes to maintaining your code, you will have to make more than one change if you change the size of buf.Code:#define FOO_LEN 5 #define BAR_LEN 10 char buf[FOO_LEN]; // changing this to BAR_LEN should not require any other changes
The macro expansion to stringify the size of the buffer and concatenate it into the format string fails in this regard. You must change the definition and the scanf call.
If you sprintf a format string, you can use the sizeof operator. But, since (as Jim pointed out) scanf does not allow for the null character, you either have to remember to do sizeof - 1. It's asking for an off-by-one error somewhere.
Last edited by anduril462; 09-11-2013 at 12:04 PM. Reason: wording fixes
This is fgets:
Code:/* fgets: get at most n chars from iop */ char *fgets(char *s, int n, FILE *iop) { register int c; register char *cs; cs = s; while (--n > 0 && (c = getc(iop)) != EOF) if ((*cs++ = c) == '\n') break; *cs = '\0'; return (c == EOF && cs == s) ? NULL : s; }