C language data input and output

Source: Internet
Author: User
Tags sprintf

1 Introduction

The C language provides cross-platform data input and output functions scanf () and printf () functions that can parse common data types in the specified format, such as integers, floating-point numbers, characters and strings, and so on. The source of data input can be files, consoles, and networks, and the output terminal can be a console, a file, or even a Web page.

2 Data output

From the first C language program, a cross-platform library function printf implementation is used to output a piece of text to the console, and in fact, printf () can not only output the data to the console in the specified format, but it can also be a Web page or a specified file.

Using the printf function to output data in a specified format to the use case of a Web page, currently our in-house IT system is also useful in C language-written Web program (CGI).

/*使用printf输出数据到网页@author Tony [email protected]@since 20160530 09:04*/printf_html() {//将生成的exe程序改成cgi就可以部署在Web服务器例如Apache中运行了,//然后通过主机名+端口+文件名.cgi的方式访问    printf("Content-type:text/html \n\n");//声明HTML语言    printf("Hello World In HTML");}

The power of the printf () function is to format the display of integers, floating-point numbers, characters, and strings. We can use this function to debug a program or get the return value of a method, and so on.
printf will only parse the data according to the type of argument passed, no data type conversion, the type and number of arguments passed in and output are consistent, or the program will run with an exception

Use printf to print a case of strings, integers, and characters

#include <stdio.h>/*    使用printf格式化输出数据    @author Tony [email protected]    @since 20160530 09:14*/void printf_sample() {    printf("Hello World \n");//输出字符串常量,默认是输出到控制台    //printf显示不同数据类型的数据    printf("我的名字叫%s,我的年龄是%d我的幸运字符是%c\n","Tony",28,‘C‘);}

printf can print out integers in three different binary types (octal, decimal, and hexadecimal), as well as in both signed and unsigned ways.
and control the width of the output characters, and so on:

#include <stdio.h>/ * Output integer data in specified format if you want to display data under a Web page, you also need to match different formats @author Tony [email protected] @since 20160530 09:20 * /voidPrintf_format_int () {Const intnum =Ten;printf("%d", num);//The default format is how wide the padding is    printf("%d\t%ld", Num,num);///32-bit systems%d and%ld are equivalent inth and long are equivalent    printf("%10d\n", num);//Width is 10, data display defaults to right alignment    printf("%010d\n", num);//width of 10, if not enough to add    printf("%-10d\n", num);//width is 10, default is aligned to the right, "-" means left justified    printf("%3d\n",12345);//m Integer, greater than the actual width, padding 0 or space, otherwise invalid}/* Output data in the specified format (with unsigned type and three types) if you want to display data under a Web page, you also need to match different formats @author Tony [email protected] @since 20160530 10: 11*/voidPrintf_format_int_data_type () {Const intnum =Ten;printf("%d\n", num);//Signed decimal    printf("%i\n", num);printf("%u\n", num);//unsigned decimal    printf("%o\n", num);//unsigned octal    printf("%x\n", num);//unsigned hex}/ * @author Tony [email protected] @since 20160530 21:53*/voidPrintf_format_int_unsinged () {unsigned  Short intUvalue =65535; Short intnum =123;printf("Uvalue =%hu\tnum=%hd", uvalue,num);}

When printf prints out floating-point numbers, the integers are all output, and by default, six digits after the decimal point, you can control the scale and width of the output by using both decimal and exponential (astronomical memory-saving) counting methods:

#include <stdio.h>/ * Output floating-point data in the specified format @author Tony [email protected] @since 20160530 10:06*/voidPrintf_format_double () {Const Doublenum =3.14159265359;printf("num=%.2f\n", num);//Two digits left after decimal point    printf("num=%030.10f\n", num);//Width 30, less than 0    //Index indication    Doubledepth =1234567000000.0;printf("depth=%e\n", depth);//Index indication    DoubleValue =1.23456789;//%g automatically selects display data with a low width%f.%e    printf("Value=%f\tvalue=%e\tvalue=%g", Value,value,value);}

printf outputs the output character through the%c format and provides the Putchar () function to output a character:

#include <stdio.h>/*    格式化输出字符    @author Tony 186017672212163.com    @since 20160530 10:15*/void printf_char() {    char‘A‘;    printf("ch=%c\n",ch);    putchar(ch);}

When printf outputs a string, the string can be spliced in the specified format by the sprintf function implementation:

/* Output string data in the specified format@authorTony18601767221@163. com@since 20160530 Ten: 08*/void Printf_format_string () {char str[ -] ="Calc";//Output stringprintf('%s\ n ', str);} /* Usesprintffunction Implementation string concatenation@authorTony18601767221@163. com@since 20160530 Ten: +*/void Sprintf_string_append () {char command[ -] = {0};sprintf(Command,"Color %c%c",' 4 ',' F ');//Consolidating integer real numbers and strings into a single stringprintf("The result of consolidation is %s\ n", command);system(command);system("Pause"); Char com[Ten] ="Task"; Char mand[Ten] ="Listerror";//command= COM + mand; C language does not have strings in the Java language to be spliced with a plus sign/*%s%sRepresents string concatenation%.4sIntercept from the left4Bits, which can only be intercepted from the left (from left to right from one address)-left justified*/    sprintf(Command,"%s%. 4s ", Com,mand);//    printf('%s\ n ', command);system(command);system("Pause");}

Using the sprintf function with a string pointer to obtain the birth date information of the ID card

/* intercept identity card by sprintf Birth date @ Author Tony [email protected] @since 20160601 14:29*/ void  sprintf_id () {char  id  [19 ] =  "421023198902345678" ; //string is terminated with a. So one more character length  printf ( "ID Number%s" ,    Span class= "Hljs-keyword" >id ); char  borndate[9 ] = { 0 }; //Initializes a string to save the date of birth  sprintf (borndate, "%-.8s" , Span class= "Hljs-keyword" >id  +6 ); //address move backward six-bit  printf ( "date of birth is%s\n" , borndate);}  

Format summary for printf () Common output data types:

format character Output Effect
%d Signed decimal integer
%lld Signed decimal integer (Long Long)
% #o unsigned octal integer (#表明进制)
% #x/% #X unsigned hexadecimal integer (#表明进制, case determines the letter case of the output data)
%u unsigned decimal integers
%llu Unsigned decimal integer (long long) for storing a social security number
%c Character
%s String
%p Pointer address
%f Floating point number
%a Hexadecimal floating-point number
%e/%e Floating-point numbers in exponential form
%g F and e compare to smaller floating-point numbers
3 Data entry

The scanf () function is primarily used to read data (usually from a file or from a user's input from the keyboard) and to accurately match parsing in the specified format.

#define _crt_secure_no_warnings#include <stdio.h>#include <stdlib.h>/ * scanf reads the input data from the user's keyboard @author Tony [email protected] @since 20160601 16:59*/voidScanf_sample () {intnum =0;printf("The address of the NUM variable is:%p\n", &num);//Print the memory address of the variable    scanf("num=%d", &num);//Initialization of variables based on address the num= integer value should be entered in the screen (for example)    printf("num=%d\n", num);intx =1, y =2, z =3;scanf("x=%d,y=%d,z=%d", &x,&y,&z);the//command-line window should enter x= integer value, y= integer values, z= integers    printf("x=%d,y=%d,z=%d", x, y, z);}

If the data type is a string, the carriage return is ignored when the scanf function is used to match the read data.

#define _crt_secure_no_warnings#include <stdio.h>#include <stdlib.h>/ * scanf exact match @author Tony [email protected] @since 20160601 17:25*/voidScanf_match () {//When using a string (character array), the input carriage return is ignored    intnum=123;Charstr[ -] = {0};scanf("%d", &num);scanf('%s ', str);printf("num=%d\n", num);printf("str=%s\n", str);}

Cases for data mining using sscanf:

#define _crt_secure_no_warnings#include <stdio.h>#include <stdlib.h>/ * Data mining with sscanf function @author Tony [email protected] @since 201060601 17:34*/voidScanf_match_data () {Chardata[ -] ="Height 170 age 22 Weight";intHeight =0;intAge =0;//Use the SSCANFH function to read the string into the variable, matching in the specified format    sscanf(Data,"%*s%d%*s%d%*s", &height,&age);//Parse the data in the specified format and read it into the variable    printf("height=%d\nage=%d\n", height,age); Height >= the&& (age >= -&& Age <= A)?printf("is the Goddess standard \ n"):printf("not the Goddess standard \ n");Charinfo[ -] ="qq,1079351401, Mobile, 18601767221, email, [email protected]";Long LongQQ =0;Long LongMobilephone =0;Charemail[ -] = {0};//The comma in the string is converted to a space because when the SSCANF function parses the string, the contents after the comma are treated as strings     for(inti =0; I < -; i++) {if(info[i]==', ') {Info[i] ="'; }    }//%*s indicates that the contents of the string are ignored    sscanf(Info,"%*s%lld%*s%lld%*s%s", &qq,&mobilephone,email);printf("qq=%lld\nmobilephone=%lld\nemail=%s\n", qq,mobilephone,email);}

When you use the SCANF function to read data, you cannot specify a precision if you are reading a floating-point number.

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>/*    scanf函数的使用注意事项    @author Tony [email protected]    @since 20160602 10:00*/void scanf_app() {    float0;    printf("请输入一个浮点数\n");    scanf("%7.2f",&fl);//scanf匹配浮点数时不能指定精度,此处将会解析数据错误    printf("fl=%f\n",fl);}

When you use scanf to read character data, a carriage return character is treated as a valid character

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>/*    scanf函数的使用注意事项    @author Tony [email protected]    @since 20160602 10:00*/void scanf_app() {    char ch1=‘0‘;    char‘0‘;    scanf("%c,%c",&ch1,&ch2);    printf("ch1=[%c],ch2=[%c]",ch1,ch2);//回车符也会被当作输入的一个字符}

Welcome to scan the QR code below, follow the public service number-art endless, share it technology dry.

C language data input and output

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.