c - How to create an input loop? -
i'm looking way write input loop continues print prompts until user enters blank line.
this want do:
loop starts, prints prompt >
command line. user enters line ends '\n', program whatever line, , prints >
again. continues until user enters blank line (\n
), @ point loop terminates.
a simple scanf
version can used:
#include <stdio.h> #define maxl 64 int main (void) { char str[maxl] = {0}; printf ("\n enter string ([enter] alone quit)\n"); while (printf (" > ") && scanf ("%63[^\n]%*c", str) == 1) { /* whatever in code */ printf (" result: %s\n", str); } return 0; }
use/output
$ ./bin/scanf_enter_quits enter string ([enter] alone quit) > string result: string > result: >
note: maxl-1
added maximum width specifier scanf
prevent write beyond end of array.
getline
example
getline
dynamically allocating line buffer allows accept line long want give it. can billions of characters (up extent of memory). strength , weakness. if need limit amount of data accept, check/validate/etc....
#include <stdio.h> #include <stdlib.h> int main (void) { char *str = null; size_t n = 0; ssize_t nchr = 0; printf ("\n enter string ([enter] alone quit)\n"); while (printf (" > ") && (nchr = getline (&str, &n, stdin)) > 1) { str[--nchr] = 0; /* strip newline input */ printf (" (str: %s)\n", str); /* whatever in code */ } if (str) free (str); return 0; }
use/output
$ ./bin/getline_enter_quits enter string ([enter] alone quit) > string 1 long want (str: string 1 long want) > string 2 make 1000 chars......................................... (str: string 2 make 1000 chars.........................................) >
scanf
dynamic allocation
you can have scanf
dynamically allocate space using m
conversion specifier (older versions of scanf
use a
conversion specifier purpose). must provide pointer-to-pointer
accept address in case. (e.g. scanf ("%m[^\n]%*c", &str)
).
#include #include
int main (void) { char *str = null; printf ("\n enter string ([enter] alone quit)\n"); while (printf (" > ") && scanf ("%m[^\n]%*c", &str) == 1) { printf (" (str: %s)\n", str); /* whatever in code */ if (str) free (str); /* must free each loop */ str = null; } if (str) free (str); return 0; }
use/output
$ ./bin/scanf_dyn_enter_quits enter string ([enter] alone quit) > string long want (str: string long want) > string length .......... ............. ............. (str: string length .......... ............. .............) >
Comments
Post a Comment