logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/may26/helloName3.c

/*
  This is similar to helloname2.c, execpt we use fgets instead of gets

  fgets is a lot safer to use than gets, because we actually can specify how many characters we will 
  be reading in, as well as where our input is coming from, so we can prevent the end-user from crashing the program

*/


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

//in addition to stdio.h, we also include string.h so that we can use the strlen function
//fgets and printf are functions inside stdio.h

int main() {

    char name[30];//creating character array for 30 characters
    			   //last character of string you input in is '\0' signifies the end of the string

    printf("Who is this? "); //prompting for a name
    fgets(name, 30, stdin);

    /*
		Above, we call fgets.

		fgets takes in three arguments: 1. the name of the array we're putting our input,
									    2. how many characters (or bytes) we are reading in
									    3. the file where our input is coming in
		
		the first argument is just the name of the array we created 

		the second argument tells us how many characters we're going to read in. if the user 
		attempts to type in more characters than what we specified, that input is simply ignored.
		this helps prevent the program from crashing, and is why it's much better to use fgets than
		gets.

		regarding the third argument, stdin is a file that refers to our own keyboard input,
		whatever we type through our own keyboard, that goes through stdin.

		in other words, the stdin at the end of fgets simply indicates that the input is going 
		to come from the user typing on the keyboard.

     */

    int len = strlen(name) - 1; //getting the length of the string, then subtracting by 1 to account for the newline character
    name[len] = '\0'; // here, we get rid of the newline character by turning it into a null character

    /*
       we did the above because unlike gets, which ignores newlines, fgets will pick up the newline character.
       and thus, in our print statement below, will actually cause the '!' character in our print string to be bumped
       to a new line. if you are fine with fgets picking up the newline, then don't do the above two lines of code   
	*/

    //printf("length of name = %d\n", len);
    printf("Hello, %s!\n", name); //prints our string
    return 0;

}