How to Read a Line of Input in C Using Fgets
C Strings
By Alex Allain
This lesson will discuss C-mode strings, which you may have already seen in the assortment tutorial. In fact, C-mode strings are really arrays of chars with a little scrap of special sauce to indicate where the cord ends. This tutorial volition embrace some of the tools available for working with strings--things like copying them, concatenating them, and getting their length.
What is a String?
Notation that along with C-style strings, which are arrays, there are too string literals, such as "this". In reality, both of these cord types are merely but collections of characters sitting next to each other in retentiveness. The only difference is that you cannot modify cord literals, whereas you tin can modify arrays. Functions that take a C-style string will be just every bit happy to have cord literals unless they alter the string (in which case your program will crash). Some things that might look like strings are non strings; in particular, a grapheme enclosed in unmarried quotes, similar this, 'a', is non a string. It's a single character, which can be assigned to a specific location in a string, but which cannot exist treated as a string. (Remember how arrays act similar pointers when passed into functions? Characters don't, so if y'all laissez passer a single character into a function, it won't work; the function is expecting a char*, not a char.)
To recap: strings are arrays of chars. String literals are words surrounded by double quotation marks.
"This is a static string"
Remember that special sauce mentioned to a higher place? Well, it turns out that C-style strings are always terminated with a null graphic symbol, literally a '\0' character (with the value of 0), and then to declare a cord of 49 letters, you demand to account for it by adding an extra grapheme, so you would want to say:
char string[l];
This would declare a string with a length of 50 characters. Practice non forget that arrays begin at zero, not 1 for the index number. In addition, we've accounted for the extra with a nil character, literally a '\0' character. It'due south important to remember that there will exist an extra character on the stop on a cord, just like there is always a catamenia at the end of a judgement. Since this string terminator is unprintable, it is not counted as a letter, but it still takes upward a space. Technically, in a 50 char array yous could only concur 49 letters and one null character at the finish to stop the cord.
Note that something like
char *my_string;
tin can as well be used as a string. If you have read the tutorial on pointers, you tin can exercise something such as:
arry = malloc( sizeof(*arry) * 256 );
which allows you lot to access arry just as if it were an assortment. To free the memory yous allocated, but use gratuitous:
For example:
free ( arry );
Using Strings
Strings are useful for holding all types of long input. If you want the user to input his or her name, yous must apply a string. Using scanf() to input a string works, but information technology will terminate the string after it reads the first space, and moreover, because scanf doesn't know how big the assortment is, information technology tin can lead to "buffer overflows" when the user inputs a cord that is longer than the size of the string (which acts as an input "buffer").
There are several approaches to treatment this trouble, only probably the simplest and safest is to use the fgets part, which is declared in stdio.h.
The image for the fgets function is:
char *fgets (char *str, int size, FILE* file);
There are a few new things here. First of all, let'due south clear upward the questions about that funky FILE* pointer. The reason this exists is because fgets is supposed to be able to read from whatever file on deejay, non simply from the user's keyboard (or other "standard input" device). For the fourth dimension being, whenever we telephone call fgets, we'll only pass in a variable called stdin, divers in stdio.h, which refers to "standard input". This effectively tells the plan to read from the keyboard. The other two arguments to fgets, str and size, are but the identify to shop the data read from the input and the size of the char*, str. Finally, fgets returns str whenever information technology successfully read from the input.
When fgets actually reads input from the user, it volition read up to size - ane characters and and then place the null terminator after the last character information technology read. fgets will read input until it either has no more room to store the information or until the user hits enter. Find that fgets may fill upwards the unabridged space allocated for str, but it volition never return a not-null terminated string to you.
Let's look at an instance of using fgets, so we'll talk about some pitfalls to watch out for.
For a example:
#include <stdio.h> int chief() { /* A nice long string */ char string[256]; printf( "Delight enter a long string: " ); /* notice stdin being passed in */ fgets ( string, 256, stdin ); printf( "Y'all entered a very long string, %s", cord ); getchar(); } Recall that yous are actually passing the accost of the array when you pass cord because arrays exercise non crave an address operator (&) to be used to pass their addresses, and then the values in the array string are modified.
The one matter to watch out for when using fgets is that it will include the newline character ('\n') when information technology reads input unless there isn't room in the string to store it. This means that you may need to manually remove the input. One fashion to practise this would be to search the cord for a newline so replace it with the cypher terminator. What would this look like? See if you can figure out a way to practise it before looking below:
char input[256]; int i; fgets( input, 256, stdin ); for ( i = 0; i < 256; i++ ) { if ( input[i] == '\north' ) { input[i] = '\0'; pause; } } Here, nosotros merely loop through the input until nosotros come to a newline, and when we exercise, we supercede it with the goose egg terminator. Find that if the input is less than 256 characters long, the user must accept striking enter, which would accept included the newline grapheme in the string! (By the way, aside from this example, in that location are other approaches to solving this trouble that use functions from string.h.)
Manipulating C strings using cord.h
string.h is a header file that contains many functions for manipulating strings. One of these is the string comparison office.
int strcmp ( const char *s1, const char *s2 );
strcmp will take two strings. It will return an integer. This integer volition either be:
Negative if s1 is less than s2. Nix if s1 and s2 are equal. Positive if s1 is greater than s2.
Strcmp performs a case sensitive comparison; if the strings are the same except for a difference in example, then they're countered equally beingness different. Strcmp as well passes the accost of the character array to the part to allow it to exist accessed.
char *strcat ( char *dest, const char *src );
strcat is brusque for "cord concatenate"; concatenate is a fancy word that means to add to the finish, or append. Information technology adds the second string to the beginning string. Information technology returns a pointer to the concatenated string. Beware this function; it assumes that dest is big enough to hold the entire contents of src besides as its ain contents.
char *strcpy ( char *dest, const char *src );
strcpy is short for string copy, which means it copies the entire contents of src into dest. The contents of dest later strcpy will be exactly the same as src such that strcmp ( dest, src ) will return 0.
size_t strlen ( const char *s );
strlen will return the length of a cord, minus the terminating grapheme ('\0'). The size_t is aught to worry about. Just care for it as an integer that cannot be negative, which is what it actually is. (The blazon size_t is simply a fashion to indicate that the value is intended for employ as a size of something.)
Here is a small program using many of the previously described functions:
#include <stdio.h> /* stdin, printf, and fgets */ #include <cord.h> /* for all the new-fangled string functions */ /* this function is designed to remove the newline from the terminate of a string entered using fgets. Annotation that since nosotros make this into its own function, we could easily choose a better technique for removing the newline. Aren't functions dandy? */ void strip_newline( char *str, int size ) { int i; /* remove the goose egg terminator */ for ( i = 0; i < size; ++i ) { if ( str[i] == '\n' ) { str[i] = '\0'; /* nosotros're done, and so merely exit the office by returning */ return; } } /* if we get all the fashion to here, there must non accept been a newline! */ } int main() { char name[50]; char lastname[fifty]; char fullname[100]; /* Large enough to hold both proper name and lastname */ printf( "Delight enter your proper noun: " ); fgets( proper noun, l, stdin ); /* run across definition above */ strip_newline( name, 50 ); /* strcmp returns zero when the two strings are equal */ if ( strcmp ( proper noun, "Alex" ) == 0 ) { printf( "That's my proper name as well.\due north" ); } else { printf( "That's not my name.\north" ); } // Find the length of your proper name printf( "Your name is %d letters long\n", strlen ( proper name ) ); printf( "Enter your last name: " ); fgets( lastname, 50, stdin ); strip_newline( lastname, fifty ); fullname[0] = '\0'; /* strcat volition expect for the \0 and add the second cord starting at that location */ strcat( fullname, proper noun ); /* Re-create name into total proper name */ strcat( fullname, " " ); /* Separate the names past a space */ strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */ printf( "Your full proper name is %south\n",fullname ); getchar(); return 0; } Safe Programming
The above string functions all rely on the existence of a naught terminator at the end of a string. This isn't ever a safety bet. Moreover, some of them, noticeably strcat, rely on the fact that the destination string can hold the entire string being appended onto the terminate. Although information technology might seem like you'll never make that sort of error, historically, issues based on accidentally writing off the end of an array in a function similar strcat, have been a major trouble.
Fortunately, in their infinite wisdom, the designers of C accept included functions designed to help you avert these issues. Like to the mode that fgets takes the maximum number of characters that fit into the buffer, at that place are string functions that take an additional statement to indicate the length of the destination buffer. For instance, the strcpy function has an analogous strncpy role
char *strncpy ( char *dest, const char *src, size_t len );
which will only re-create len bytes from src to dest (len should be less than the size of dest or the write could still go beyond the bounds of the array). Unfortunately, strncpy tin lead to one niggling effect: it doesn't guarantee that dest will have a null terminator attached to it (this might happen if the string src is longer than dest). You can avoid this trouble by using strlen to get the length of src and brand sure it will fit in dest. Of class, if you were going to do that, then you probably don't need strncpy in the first place, right? Incorrect. Now it forces you to pay attending to this issue, which is a large part of the boxing.
Quiz yourself
Previous: Arrays
Side by side: File I/O
Back to C Tutorial Alphabetize
Source: https://www.cprogramming.com/tutorial/c/lesson9.html
0 Response to "How to Read a Line of Input in C Using Fgets"
Postar um comentário