Skip to content

Instantly share code, notes, and snippets.

@itay-grudev
Last active July 3, 2016 13:58
Show Gist options
  • Save itay-grudev/37f1a64e49fcad2edf13 to your computer and use it in GitHub Desktop.
Save itay-grudev/37f1a64e49fcad2edf13 to your computer and use it in GitHub Desktop.
Get data from a stream until EOF ignoring whitespace
#include <cstdio>
#include <cstdlib>
/**
* @brief getlnw Get data from a stream until EOF ignoring whitespace
* @param input the given input stream
* @return returns a pointer to the string.
* @note you have to free() the string manually
*/
char* getlnw( FILE *input = stdin )
{
char *str;
unsigned int length = 0;
str = (char*)malloc( sizeof(char) );
str[0] = '\0';
short chr;
while( (chr = getc( input )) != EOF )
{
switch ( chr ) {
case ' ':
case '\t':
case '\n':
continue;
break;
}
str[length] = (char)chr;
length += 2;
str = (char*)realloc( str, length + 1 );
--length;
str[length] = '\0';
}
return str;
}
int main( int argc, char *argv[] )
{
// A newline before the Ctrl+D may be required to force flushing the stdin buffer
printf( "Enter string (Press Ctrl+D to terminate input)" );
char *crypto = getlnw();
printf( "string: %s\n", crypto );
free( crypto );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment