A function to read a string terminated by an arbitrary character
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
char* getString(char *buffer, char end_char);
int main()
{
char buffer[MAX_SIZE];
int i = 0;
printf("Enter a string terminated by a semi-colon:\n");
getString(buffer, ';');
printf(":\n%s\n", buffer);
}
char* getString(char *buffer, char end_char)
{
size_t i = 0;
/* Read a character until end_char is entered */
while((buffer[i++] = getchar()) != end_char)
;
buffer[i-1] = '\0'; /* Overwrite end_char with string terminator */
return buffer;
}
Related examples in the same category