Skip to content

Instantly share code, notes, and snippets.

@bradjohansen
Created July 23, 2010 16:51
Show Gist options
  • Save bradjohansen/487698 to your computer and use it in GitHub Desktop.
Save bradjohansen/487698 to your computer and use it in GitHub Desktop.
cs50 GetString()
// [...]
/*
* string
* GetString()
*
* Reads a line of text from standard input and returns it as a string,
* sans trailing newline character. (Ergo, if user inputs only "\n",
* returns "" not NULL.) Leading and trailing whitespace is not ignored.
* Returns NULL upon error or no input whatsoever (i.e., just EOF).
*/
string
GetString()
{
// growable buffer for chars
string buffer = NULL;
// capacity of buffer
unsigned int capacity = 0;
// number of chars actually in buffer
unsigned int n = 0;
// character read or EOF
int c;
// iteratively get chars from standard input
while ((c = fgetc(stdin)) != '\n' && c != EOF)
{
// grow buffer if necessary
if (n + 1 > capacity)
{
// determine new capacity: start at CAPACITY then double
if (capacity == 0)
capacity = CAPACITY;
else if (capacity <= (UINT_MAX / 2))
capacity *= 2;
else
{
free(buffer);
return NULL;
}
// extend buffer's capacity
string temp = realloc(buffer, capacity * sizeof(char));
if (temp == NULL)
{
free(buffer);
return NULL;
}
buffer = temp;
}
// append current character to buffer
buffer[n++] = c;
}
// return NULL if user provided no input
if (n == 0 && c == EOF)
return NULL;
// minimize buffer
string minimal = malloc((n + 1) * sizeof(char));
strncpy(minimal, buffer, n);
free(buffer);
// terminate string
minimal[n] = '\0';
// return string
return minimal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment