The input and output of characters in C language and the method of calculating the number of characters _c language

Source: Internet
Author: User
Tags numeric value

C language character input and output

The input/output model provided by the standard library is very simple. Regardless of where the text is entered and where it is exported, its input/output is handled in the same way as a stream of characters. A text flow is a sequence of characters consisting of multiple lines of characters, and each line of characters consists of 0 or more characters, and the end of a line is a newline character. The standard library is responsible for making each input/output stream conform to this model. C programmers using a standard library do not have to care about how these lines are represented outside of the program.

The standard library provides a function to read/write one character at a time, the simplest of which is the GetChar and Putchar two functions. Each time it is invoked, the GetChar function reads the next input character from the text stream and returns it as the result value. In other words, in executing the statement
c = GetChar ()
Later, the variable C will contain the next character in the input stream. This type of character is usually entered through the keyboard.

One character is printed each time the Putchar function is called. For example, the statement

Putchar ()

The contents of the integer variable C are printed as characters, usually on the screen. Putchar and printf The two functions can be invoked alternately, and the order of the outputs is the same as the order of the calls.

With the help of the GetChar and Putchar functions, you can write surprisingly useful code without knowing other input/output knowledge. The simplest example is to copy the input one character at a time to the output, the basic idea is as follows: Fu
Read a character
While (this character is not a file end indicator)
Output the characters you just read
Read the next character
Translate the above basic idea into the C language program as follows:

#include <stdio.h>
/* Copy input to output 1st version*/
Main ()
{
 int c;
 c = GetChar ();
 while (c!= EOF) {
 Putchar (c);
 c = GetChar ();
 }
}

Where the relational operator!= represents "not equal to".

Characters are stored in bit mode inside the machine, in whatever form the keyboard, screen, or any other place is displayed. The char type is specifically used to store this type of character data, and of course any integer (int) can also be used to store character data. For some potentially important reason, we use the int type here.

Here's how to distinguish between valid data in a file and an input terminator. The C language solution is that, without input, the GetChar function returns a special value that is different from any actual character. This value is called EOF (end of file, ending of files). When we declare variable C, we must make it large enough to hold any value returned by the GetChar function. The reason for not declaring C as a char type is that it must be large enough to store the end of the file, EOF, in addition to storing any possible characters. Therefore, we declare C to be of type int.

EOF is defined in header file <stdio.h>, it is an integer, and its specific value is not important, as long as it is different from any value of char type. Using symbolic constants here, you can ensure that your program does not depend on any particular numeric value that it corresponds to.

For the more experienced C language programmers, you can write this character copy program more refined. In the C language, similar to the

c = GetChar ()

The assignment operation is an expression that has a value, that is, the value that the left variable holds after the assignment. In other words, the assignment can appear as part of a larger expression. If you place a value assignment for C in the test section of the while Loop statement, the character replicator can be changed to the following form:

#include <stdio.h>
/* Copy input to output 2nd version
*
/Main ()
{
 int c;
 while ((c = GetChar ())!= EOF)
 Putchar (c);
}

In the program, the while Loop statement first reads a character and assigns it to C, and then tests whether the character is a file end flag. If the character is not a file end flag, the while statement body is executed and the character is printed. The while statement is then repeated. When the end of the input is reached, the while Loop statement terminates execution, thus ending the entire main function execution.

The above program will be input centralized, the GetChar function only appears once in the program, this shortens the program, the whole program looks more compact. Accustomed to this style, the reader will find that the program written in this way is easier to read. We often see this style. (However, if we use this type of complex statement too much, the program that is written may be difficult to understand and should be avoided as much as possible.) )

The parentheses on either side of an assignment expression cannot be omitted from the conditional part of the while statement. The precedence of the operator!= is not equal to the precedence of the assignment operator =, so that the relationship test!= will be executed before the assignment = operation without the use of parentheses. So the statement

c = GetChar ()!= EOF

Equivalent to statement

c = (GetChar ()!= EOF)

After the statement executes, the value of C will be set to 0 or 1 (depending on whether the file end flag is invoked when the GetChar function is called), which is not what we want.

Count characters
The following programs are used to count characters:

#include <stdio.h>/

* Statistics The number of characters entered Version 1.0
/main ()
{
 long NC;
 
 NC = 0;
 while (GetChar ()!= EOF)
  ++nc;
 printf ("%ld\n", NC);
}

Among them, the statement ++nc; A new operator + + is introduced with the function of adding 1 operations. You can replace it with statement NC = NC + 1, but the statement ++nc is more refined and generally more efficient. The corresponding operator is the self-decrement operator--。 + + and--these two operators can be either prefix operators (such as ++NC) or as suffix operators (such as nc++). As we'll see later, the two forms have different values in the expression, but both ++nc and nc++ increase the value of the NC by 1. For now, we use only the prefix form.

The character-counter program uses a long variable to hold the count value instead of using a variable of type int. A long integer (Long integer) occupies at least 32 bits of storage unit. int is the same length as long on some machines, but on some machines, the value of type int may only have a length of 16-bit storage cell (the maximum is 32767), so a fairly small input can overflow the count variable of type int. The conversion specification%ld tells the printf function that its corresponding argument is a long integer.

Use double (double-precision floating-point number) types to handle larger numbers. Instead of using a while loop statement, we use the FOR Loop statement to show another way to write this loop:

#include <stdio.h>

/* Count characters in input 2nd version *
/main ()
{
 double NC;
 for (NC = 0; GetChar ()!= EOF; ++nc)
 ;
 printf ("%.0f\n", NC);
}

For float and double types. The printf function is described using%f. The%.0f force does not print decimal points and fractional parts, so the decimal part has a number of digits of 0.

In the program section, the loop body of the FOR Loop statement is empty because all work is done in the test (condition) section and the Increment step section. However, the grammar rules of the C language require that the FOR Loop statement must have a loop body, thus substituting a separate semicolon. A separate claim is an empty statement that satisfies the requirement for a for statement. Put it on one line alone in order to be more eye-catching.

Before you end the discussion of the character Count program, we consider the following situation: if the input does not contain characters, then the first call to the GetChar function, the while statement or the for statement in the conditional test is false from the start, the program's execution result will be 0, which is also the correct result. This is important. One of the advantages of a WHI1E statement and a for statement is that the condition is tested before executing the loop body, and if the condition is not satisfied, the loop body is not executed, which may occur when the loop body is not executed at once. In the case of 0-length input, the process should be flexible, and when boundary conditions occur, the while statement and the for statement help ensure that the program performs reasonable operations.

To connect a two-string program:

#include <stdio.h>
#include <string.h>
void Main ()
{
 int i;
 Char str1[30]= "Welcome to";
 Char str2[]= "www.nowamagic.net";
 printf ("%s\n", strcat (STR1,STR2));
 scanf ("%d", &i);
}

To implement a program that evaluates strings under MFC:

void Cnowamagic_mfcdlg::onbnclickedok ()
{
 //TODO: Add control Notification Handler code
 //cdialogex::onok () here;
 Get edit 
 cedit* pboxone; 
 Pboxone = (cedit*) GetDlgItem (idc_edit1); 

 CString str;
 CString Sstrlen; 
 Char tmp[10] = "";

 pboxone-> GetWindowText (str); 
 int nstrlen = str. GetLength ();
 Sstrlen = itoa (nstrlen,tmp,10);
 CString str2 = _t ("Number of characters:");

 MessageBox (str2 + sstrlen,_t ("program run Result"), MB_OK);
 Str. ReleaseBuffer ();
}

The results of the program operation are as follows:

In order to better program practice, the recommended use of MFC also put the program to practice, have the UI out of fun will be even greater.

Some details are as follows:

Define char tmp[10] = ""; If you do not specify the length of the array, memory is out of bounds.
with Str. GetLength (); method to get the length of the CString.
Itoa (int,str,10) converts an integer to a string. int is the integer that you want to turn, and STR is the string that holds the turn, and 10 is the pattern (and other patterns). The
Connect two CString can be directly used with the + operator.

Related Article

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.