I wrote this small program that will truncate a string that's entered in by the user.
An example of its usage:
if the user enters in a string say "abcdefghijklmnopqrstuvwxyz" the program will only take the first 9 characters and truncate the rest so that the user can be prompted for a second string and not be worried about remaining characters left in the stream.
Now this program works O.K. but I would like to find something in C that has this functionality build into it...Does anyone know of any function that will accomplish this...
Code:
#include <stdio.h>
#include <stdlib.h>
#define BSIZE 10
void getstring(char *s, FILE *fd, int size)
{
int i = 0;
while ((s[i++] = fgetc(fd)) != '\n')
{
if (i > size) --i;
}
s[--i] = '\0';
}
int main(int argc, char**argv)
{
char testch1[BSIZE];
char testch2[BSIZE];
fputs("enter a test string~>", stdout);
getstring(testch1, stdin, (BSIZE - 1));
fprintf(stdout, "string~>%s\n", testch1);
fputs("enter a test string~>", stdout);
getstring(testch2, stdin, (BSIZE - 1));
fprintf(stdout, "string~>%s\n", testch2);
exit(EXIT_SUCCESS);
}