Input and output of strings

Source: Internet
Author: User

C-language string representation

Strings are the most commonly used and most important data types in C, but the C language does not specifically provide this type . Because strings are made up of characters, we declare strings, and we use character arrays. A character array is a variable representation of a string. The difference and connection between a pure character array and a string is that the string is an array of characters ending with ' /'. Therefore, we declare a character array char ch[32] In fact it can store up to 31 characters, and the last character is ' \ S ', which is the flag at the end of the string.

The string also has a representation method, which is a string constant (string literal). For example printf ("%s", "King and Queen"); "King and Queen" is a string constant in this expression statement. In fact, it is also an array of elements as character constants, the contents of this array are (char []) {' K ', ' I ', ' n ', ' g ', ' ', ' a ', ' n ', ' d ', ', ' Q ', ' u ', ' e ', ' e ', ' n ', ' + '}; Be careful not to forget ' the '.

Because string constants such as "Anytime" can represent the first address of this string, which is exactly an array of character constants for the element. Therefore, we can manipulate strings with pointers. We can make a reputation like this:

Char " Anytime ";

But not like this:

Char * chptr; " Anytime ";

Because *chptr represents the contents of the address pointed to by chptr, if this pointer is not initialized, then this is a very dangerous operation, the pointer may randomly point to the memory space, if the point is the system file, it will modify the system files. We should not do this even if the pointer has been initialized for two reasons:

1. Doing so may result in overflow (beyond the safe memory space)

2. Will change what should not be changed (see this article for a good explanation)

Therefore, pointer manipulation string constants are not safe and are generally used only to transfer the address of a string variable (the content is an array of character variables).

String Basic output

SCANF () has a dedicated%s to enter a string, but its terminating condition is that it encounters whitespace characters such as spaces, line breaks, and so on. Rather, it is used to handle word input. While processing a long string input, the first is to use the Get (), when it reads the newline character discard ' \ n ' and end the input, it is very useful (for earlier), but I do not want you to master it, although a lot of random programs are using it.

Char cha[5];gets (cha);

This function is really useful, just put the first address of the array into the line. Can you notice a serious flaw? This function does not know the size of this array, that is, it does not know the maximum number of characters it can accept input, which will cause overflow! Some of the UNIX system's code used a lot of gets (), which gives hackers the opportunity to write garbage data to the system through this vulnerability writer, which is a worm that is prevalent among these UNIX computers.

I recommend that you use the fgets () function, which is safer to use than get (), but more cumbersome.

Char * cha[//fgets (name, size, read file)//  If you want to use this function to read from the keyboard, please use the stdin where you read the file.

The incoming size is n, which terminates when it reads a maximum of n-1 characters or encounters a newline character. For example, after I enter "1234567890123456" after the code above runs, cha = "123456789012345". This function looks perfect, but the perfect thing doesn't exist. The flaw with fgets () is that it saves line breaks when it reads a newline character! The following is an example of a program for C Primer plus version fifth:

  At this point, it is very urgent to write a function that discards the fgets () saved newline character and the subsequent invalid characters. If you do not discard the invalid character, it will cause the subsequent statement to read the buffer mistakenly, just like a beginner character input when entering a character enter after entering a character, but no input has been executed to the back. We named our own function s_gets (), and we let it return the same value as the return value of fgets (). The function code we write is as follows:

1 Char* S_gets (Char* Sptr,intsize) {2     inti =0;//I indicates the number of reads3     Char* RE;//re returns the same value as fgets ()4Re =fgets (Sptr,size,stdin);5     if(RE) {//if re! = NULL6          while((sptr[i]! ='\ n') && (sptr[i]! =' /') )//Read Sptr[i] until you read '/\ n '7i++;8         if(Sptr[i] = ='\ n')//if you read ' \ n '9Sptr[i] =' /';//Turn it into ' a 'Ten         Else One              while((GetChar ())! ='\ n')//If you read something else, read ' \ n ' to prevent subsequent statements from misreading . A                 Continue; -     } -     returnre; the}

If a secure string input is needed in the future, this function will be OK. Use the example of this function to run:

String Basic input

The printf () function provides a close-to-perfect string output, and it can also output numbers directly (such as%d,%u, etc.). The printf () function is very versatile, so be sure to remember this if you don't want to use any other string output function. I believe that even beginners who have just learned C know how to use this function.

The puts () function is simple and easy to use, giving the address of the string directly. It is important to note that the puts () function is added ' \ n ' after the string output, so puts () and get () and the s_gets () that we wrote above are used.

Char cha["Memory"; puts (cha);

  Fputs () function mainly and fgets (), need to be reminded that these two functions can not only be used on the standard I/O, but also for file processing, and is generally used in file processing. The fputs () function requires two parameters, the first parameter gives the string address, and the second parameter gives the output position. Because it is used in conjunction with fgets (), it does not add ' \ n ' after the output string.

Char * cha["memory\n"; fputs (Cha,stdin);

  The following examples are given in C Primer plus version fifth:

Write your own custom string input and output function!

  You can also write your own input and output functions yourself, and assume that the functions you write are not much more reliable and flexible than most of the functions mentioned above. We can use GetChar () and Putchar () to complete the input and input functions of strings.

The following is the function I wrote, the reader after reading should also write their own, perhaps later can use it!

1#include <stdio.h>2#include <stdlib.h>3 4 #defineSIZE 165 6 Char* Ud_gets (Char* St,intSize) {//input7     inti =0;//counter8      while(((St[i] = GetChar ())! ='\ n') && (i < size-1) )9i++;//Continue reading if non ' \ n ' characters are read or not out of boundsTen      while((I > Size-1) && (GetChar ()! ='\ n')) One         Continue;//if the read exceeds the bounds and there are characters later, discard ASt[i] =' /';//End Read -     returnSt; - } the  - Char* Ud_puts (Char* St,intAd_enter) {//Output -     inti =0; -      while(Putchar (st[i])! =' /')//If you do not read to the end of the string, continue reading +i++; -     if(Ad_enter)//if the switch with ' \ n ' is turned on +Putchar ('\ n');//Output line breaks A     returnSt; at } -  - intMainintargcChar*argv[]) { -     CharCha[size]; - ud_gets (cha,size); -Ud_puts (CHA,0); in getch (); -     return 0; to}

  Operation Result:

  

Input and output of strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.