This code is an implementation of a function which reads a string from standard in using pure C code that I did in high school for a programming class. The test.c program is used to test the function works properly. The code is limited to reading strings of 255 characters long and there is no error handling or reporting.

get_string.c

/*******************************************************************
*	get_string
*
*	char* get_string(const char* prompt, char* buffer, char* default);
*
*	a function that will read from the the keyboard and return a
*	string in a buffer to be read by the user. default is a string
*	to be returned on the case that the user types only an enter
*	key.
*
********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* get_string(const char prompt[256], char buffer[256], char error[256]){
	//declare the variables
	int counter;

	//print the users prompt
	printf("%s",prompt);

	//before scanning, make sure the buffer is cleaned out...
	rewind(stdin);

	//read in a string
	fgets(buffer, 256, stdin);

	//check for the enter only condition
	if(buffer[0] == '\n'){
		printf("%s", error);
		buffer = "\0";
		return(buffer);
	}

	//check for exceeding the limits of the buffer
	if(strlen(buffer) > 255){
		printf("\nERROR: EXCEEDED THE CHARACTER LIMIT\n");
	}

	//check for the special q case
	if(tolower(buffer[0]) == 'q'){
		exit(0);
	}

	//get rid of the newline
	for(counter = 0; counter < 256; counter ++){
		if(buffer[counter] == '\n'){
			buffer[counter] = '\0';
		}
	}

	//return the string...
	return(buffer);
}

test.c

//tests my get_string function...
#include <stdio.h>


char* get_string(char* prompt, char* buffer, char* death);

int main(void){
	char prompt[256] = "\nEnter your name: ";
	char error[256] = "\nPlease enter something: ";
	char buffer[256];

	printf("%s", get_string(prompt, buffer, error));
}

 

Log in to comment