We recommended you to check C Arrays and Pointers before you check this example. Hence, you can use pointers to manipulate elements of the string. Similar like arrays, string names are "decayed" to pointers. Learn more about passing arrays to a function.Įxample 3: Passing string to a Function #include ĭisplayString(str) // Passing string to a function. Strings can be passed to a function in a similar way as arrays. It's because gets() allows you to input any length of characters. However, it is removed from the C standard. Note: The gets() function can also be to take input from the user. To print the string, we have used puts(name). Hence, we can take a maximum of 30 characters as input which is the size of the name string. Here, we have used fgets() function to read a string from the user.įgets(name, sizeof(name), stdlin) // read string And, you can use puts() to display the string.įgets(name, sizeof(name), stdin) // read string You can use the fgets() function to read a line of string. Thus, the name in scanf() already points to the address of the first element in the string, which is why we don't need to use &. This is because name is a char array, and we know that array names decay to pointers in C. It's because there was a space after Dennis.Īlso notice that we have used the code name instead of &name with scanf(). The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).Įxample 1: scanf() to read a string #include Įven though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the name string. You can use the scanf() function to read a string. Note: Use the strcpy() function to copy the string instead. For example, char c Ĭ = "C programming" // Error! array type is not assignable. This is bad and you should never do this.Īrrays and strings are second-class citizens in C they do not support the assignment operator once it is declared. Here, we are trying to assign 6 characters (the last character is '\0') to a char array having 5 characters. Let's take another example: char c = "abcde" Octal values, hexadecimal values, and decimal values can be stored in int data type in C. char c = "abcd" Ĭhar c = String Initialization in C Data types in C programming language enables the programmers to appropriately select the data as per requirements of the program and the associated operations of handling it. The following are some main primitive data types in C: Integer Data Type The integer datatype in C is used to store the integer numbers (any number including positive, negative and zero without decimal part). You can initialize strings in a number of ways. Here, we have declared a string of 5 characters. Here's how you can declare strings: char s String Declaration in C
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |