Skip to content

Instantly share code, notes, and snippets.

@kahless62003
Last active September 30, 2016 00:07
Show Gist options
  • Save kahless62003/ee496659baba8227f187fb2de8fd24c0 to your computer and use it in GitHub Desktop.
Save kahless62003/ee496659baba8227f187fb2de8fd24c0 to your computer and use it in GitHub Desktop.
Modified program for repeated input and transfer of chars between arrays
#include <stdio.h>
#include <string.h>
//moved the fixed sizes to defines and have 2. 1 for the main buffer, and one for the name fields
#define maxinput 256
#define maxname 16
int main()
{
char input[maxinput];//large buffer to accept more input than name fields allow - note that too can overflow as the value is fixed
char firstname[maxname];
char lastname[maxname];
char caniexit; //character switch variable
int temp_length, lc; //integers - store strlen result in a variable to avoid recalculating each time, loop counter
caniexit = 'n'; //initiallise switch to n
while (caniexit == 'n') //start while loop to loop until caniexit is not n
{
printf("Type your first name: ");
fgets(input,maxinput,stdin);
temp_length = strlen(input);
if ( input[temp_length-1] == '\n')
input[temp_length-1] = '\0';
temp_length = strlen(input);//if the new line was replaced, the string length is now different
if (temp_length >= maxname)//check for correct length
printf("Error: name too long, enter 15 or fewer characters.\n");
else
caniexit = 'y';//if length ok, set switch to y in order to allow loop exit
}
//Left behind after adding above loop to ensure name fits, but this bit limits the number of characters to transfer to the name variable to 15
if ( temp_length >= maxname)
temp_length = maxname-1;
//start for loop - type of while for counting sequentially through a range of numbers and acting on each value.
// first part start the loop counter at zero; next while the counter is less than the length of the string; increment counter after each run of the loop
for (lc=0; lc < temp_length; lc++)
firstname[lc] = input[lc];
firstname[lc] = '\0';
caniexit = 'n';
while (caniexit == 'n')
{
printf("Okay, %s, now tell me your last name: ",firstname);
fgets(input,maxinput,stdin);
temp_length = strlen(input);
if ( input[temp_length-1] == '\n')
input[temp_length-1] = '\0';
temp_length = strlen(input);
if (temp_length >= maxname)
printf("Error: name too long, enter 15 or fewer characters.\n");
else
caniexit = 'y';
}
if ( temp_length >= maxname)
temp_length = maxname-1;
for (lc=0; lc < temp_length; lc++)
lastname[lc] = input[lc];
lastname[lc] = '\0';
printf("Pleased to meet you, %s %s.\n",firstname,lastname);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment