Examples of data input and output in C language

  • 2020-05-24 05:54:40
  • OfStack

C data input and output examples

1 introduction to

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

2 data output

From the first c language program, the cross-platform library function printf is used to output 1 paragraph of text to the console. In fact,printf() can output data not only to the console in a specified format, but also to a web page or a specified file. The return result of the printf() function is the number of output characters.

2.1 output data to web pages

Use cases where the printf function is used to output data to a web page in a specified format. Currently, our company's internal IT system also has a web page program written in C language (cgi).


#include <stdio.h>
/*
 use printf Output data to web pages 
@author Tony 18601767221@163.com
@since 20160530 09:04
*/
void printf_html() {
// The generated exe The program to cgi Can be deployed in Web Servers such as Apache In the cgi-bin Once you run it in the directory, you can access it. 
// Then go through the host name + port + The file name .cgi Way to access 
  printf("Content-type:text/html \n\n");// The declared output data format is HTML language 
  printf("Hello World In HTML");
}

2.2 integer formatted output

The power of the printf() function is to format and display output integers, floating point Numbers, characters, and strings to files, web pages. At the same time in the console we can use this function to debug the program or get the return value of the method and so on.

The printf function is represented as :printf(" formatted string data ", mutable argument list)

printf will only parse the data according to the passed parameter types, and will not conduct data type conversion. The input parameter types and Numbers and the output parameter types and Numbers are kept at 1, otherwise an exception will occur when the program runs

Example of printing strings, integers, and characters using printf


#include <stdio.h>
/*
   use printf Formatted output data 
  @author Tony 18601767221@163.com
  @since 20160530 09:14
*/
void printf_sample() {
// The output is eventually printed as a string 
  printf("Hello World \n");// Output string constants, which are output to the console by default 
  //printf Displays data of different data types 
  printf(" My name is %s, My age is %d My lucky character is %c\n","Tony",28,'C');
}

When printing out integers, printf not only prints integers in three different base types (8,10, and 106), but also in both signed and unsigned forms.

And controlling the width of the output characters, and so on:


#include <stdio.h>
/*
   Outputs integer data in the specified format 
   If you want to display data under a web page , You also need to use printf Implement matching of different data formats 
  @author Tony 18601767221@163.com
  @since 20160530 09:20 
*/
void printf_format_int() {

  const int num = 10;
  printf("%d",num);// How wide is the default format   Fill more wide 
  printf("%d\t%ld",num,num);//32 Bit above system %d and %ld Is the equivalent of  inth and long Is the equivalent of 
  printf("%10d\n",num);// Width is 10, The data display defaults to right alignment 
  printf("%010d\n",num);// Width is 10, If not, use it 0 To supplement the 
  printf("%-10d\n",num);// Width is 10, The default is to align to the right , "-" That means left aligned 
  printf("%3d\n",12345); //12345 Larger than the actual width, 3d Invalid format, insufficient to fill with Spaces 

/*
   Outputs an integer of the specified format ( Unsigned types as well 3 Of a species type ) data 
   If you want to display data under a web page , You also need to match different formats 
  @author Tony 18601767221@163.com
  @since 20160530 10:11
*/
void printf_format_int_data_type() {

  const int num = 10;
  printf("%d\n", num);// A signed 10 Into the system 
  printf("%i\n",num);
  printf("%u\n",num); // unsigned 10 Into the system 
  printf("%o\n",num);// unsigned 8 Into the system 
  printf("%x\n",num); // unsigned 106 Into the system 

}
/*
  @author Tony 18601767221@163.com
  @since 20160530 21:53
*/
void printf_format_int_unsinged() {

  unsigned short int uvalue = 65535;
  short int num = 123;

  printf("uvalue =%hu\tnum=%hd",uvalue,num);
}

2.3 format the output for floating point Numbers

When printing out floating point Numbers, printf outputs all the integers, keeping 6 decimal places by default. It can count both decimal Numbers and scientific counting method (scientific counting method is used to save memory for astronomical Numbers). At the same time, it can control the number of decimal places and the width of the output:


#include <stdio.h>
/*
   Outputs floating-point data in the specified format 
  @author Tony 18601767221@163.com
  @since 20160530 10:06
*/
void printf_format_double() {

  const double num = 3.14159265359;
  printf("num=%.2f\n", num);// We keep two decimal places 
  printf("num=%030.10f\n",num);// Width is 30 Insufficient, with 0 Make up, otherwise output according to the actual width 

  // Scientific notation 
  double depth = 1234567000000.0;
  printf("depth=%e\n",depth);// Index said 


  double value = 1.23456789;// %g  Automatically select display data with less width  %f.%e
  printf("value=%f\tvalue=%e\tvalue=%g",value,value,value);

}

2.4 format output characters and strings

printf outputs characters via the %c format character and provides the putchar() function to output 1 character:


#include <stdio.h>
/*
   Formatted output character 
  @author Tony 186017672212163.com
  @since 20160530 10:15
*/
void printf_char() {
  char ch = 'A';
  printf("ch=%c\n",ch);
  putchar(ch);
}

When printf outputs a string, it can concatenate the string in the specified format through the sprintf function:


#include <stdio.h>
/*
   Outputs string data in the specified format 
  @author Tony 18601767221@163.com
  @since 20160530 10:08
*/
void printf_format_string() {
  char str[100] = "calc"; // Output string 
  printf("%s\n",str);
}

/*
   use sprintf The function implements string concatenation 
  @author Tony 18601767221@163.com
  @since 20160530 10:32
*/
void sprintf_string_append() {
  char command[100] = { 0 };
  sprintf(command, "color %c%c", '4', 'f');// The integer   Real Numbers and strings are integrated into 1 A string 
  printf(" The result of integration is %s\n", command);
  system(command);
  system("pause");

  char com[10] = "task";
  char mand[10] = "listerror";

  //command = com + mand; C Language is not Java Strings in a language are concatenated with a plus sign 

  /*
    %s%s Represents string concatenation 
    %.4s  From the left 4 position , Only from the left ( On the one 1 The address is intercepted from left to right )
    - The left alignment 
  */
  sprintf(command,"%s%.4s",com,mand);//
  printf("%s\n",command);
  system(command);
  system("pause");
}

The date of birth information of id card is obtained by using sprintf function and string pointer


/*
   through sprintf Intercepts the identity card the date of birth 
  @author Tony 18601767221@163.com
  @since 20160601 14:29
*/
void sprintf_id() {

  char id[19] = "421023198902345678"; // The string is \0 At the end   So you have to pay more 1 Length of characters 
  printf(" The id number is %s",id);

  char bornDate[9] = {0}; // Initialize the 1 Number of strings to hold the date of birth 
  sprintf(bornDate,"%-.8s",id+6);// The address moves back 6 position 
  printf(" Date of birth %s\n",bornDate);
}

2.5 printf formats a summary of the parameters of the output data

格式符 解析方式
%hd 有符号10进制短整数(short)
%hu 无符号10进制短整数(unsinged short)
%d 有符号10进制整数(int或者long)
%lld 有符号10进制整数(long long)
%#o 无符号8进制整数(#表明进制)
%#x/%#X 无符号106进制整数(#表明进制,大小写决定了输出数据的字母大小写)
%u 无符号10进制整数
%llu 无符号10进制整数(long long)用于存储身份证号
%c 字符
%s 字符串
%p 指针地址
%f 浮点数
%a 106进制浮点数
%e/%E 指数形式的浮点数
%g f和e相比宽度更小的浮点数

3 data input

The scanf() function is primarily used to read data (usually from a file or user input from the keyboard) and match it exactly to the specified format (no characters are omitted). Most parsed data is formatted in the same format as printf()1. When scanning to read integers, floating point Numbers, and characters, variable names are usually appended with address characters ( & ), the variable name does not need an address when the scan reads the string. The scanf function returns the number of input data successfully read

The 1 common form of the scanf() function is scanf(" format string ", variable address table)


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

/*
  scanf Reads the user's input data from the keyboard 
  @author Tony 18610767221@163.com
  @since 20160601 16:59
*/
void scanf_sample() {
  int num = 0;
  printf("num The address of the variable is :%p\n",&num); // Print the memory address of the variable 
  scanf("num=%d",&num); // Initialize and assign a variable according to the value of the variable corresponding to the address   The console should enter num= An integer value ( For example, 12)
  printf("num=%d\n",num);

  int x = 1, y = 2, z = 3;// Declare multiple integers 
  scanf("x=%d,y=%d,z=%d",&x,&y,&z);// The command line window should be entered x= An integer value ,y= An integer value ,z= An integer value   The format string must match exactly 
  printf("x=%d,y=%d,z=%d",x,y,z);
  system("pause");

}

When using the scanf function to match read data, carriage returns are ignored if the data type is a string.


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
/*
  scanf An exact match 
  @author Tony 18601767221@163.com
  @since 20160601 17:25
*/
void scanf_match() {
  // When using strings ( A character array ) when , Enter is ignored 
  int num=123;
  char str[100] = { 0 };
  scanf("%d", &num);// Scan read num
  scanf("%s",str);// Scan read string 

  printf("num=%d\n",num);
  printf("str=%s\n",str);
  system("pause");
}

Examples of data mining using sscanf:

You can use the enter key space or Tab to implement the end of data reading when reading multiple data once


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
/*
   use sscanf The function implements data mining 
  @author Tony 18601767221@163.com
  @since 201060601 17:34
*/
void scanf_match_data() {

  char data[300] = " height  170  age  22  weight  96 ";// A space indicates the end of the read 
  int height = 0;
  int age = 0;
  // use sscanfh The function reads a string into a variable , Matches in the specified format 
  sscanf(data, "%*s %d %*s %d %*s",&height,&age); // The data is parsed in the specified format and read into variables 

  printf("height=%d\nage=%d\n",height,age);
  height >= 170 && (age >= 20 && age <= 22)?printf(" It's the goddess standard \n"):printf(" Not the goddess criterion \n");

  char info[300] = "QQ,1079351401, Mobile phone ,18601767221, email ,18601767221@163.com";
  long long qq = 0;
  long long mobilePhone = 0;
  char email[30] = {0};

  // Start with the comma in the string , Convert to space   Because when sscanf Function for string parsing , Everything after a comma is treated as a string 
  for (int i = 0; i < 300;i++) {
    if (info[i]==',') {
      info[i] = ' ';
    }
  }
  //%*s Means to ignore the contents of the string 
  sscanf(info,"%*s %lld %*s %lld %*s %s",&qq,&mobilePhone,email);
  printf("qq=%lld\nmobilePhone=%lld\nemail=%s\n",qq,mobilePhone,email);
  system("pause");

}

When reading data using the scanf function, you cannot specify the precision if you are reading a floating point number.


#include <stdio.h>
/*
   use printf Formatted output data 
  @author Tony 18601767221@163.com
  @since 20160530 09:14
*/
void printf_sample() {
// The output is eventually printed as a string 
  printf("Hello World \n");// Output string constants, which are output to the console by default 
  //printf Displays data of different data types 
  printf(" My name is %s, My age is %d My lucky character is %c\n","Tony",28,'C');
}
0

When using scanf to read character data, carriage return, escape character and so on will be regarded as a valid character


#include <stdio.h>
/*
   use printf Formatted output data 
  @author Tony 18601767221@163.com
  @since 20160530 09:14
*/
void printf_sample() {
// The output is eventually printed as a string 
  printf("Hello World \n");// Output string constants, which are output to the console by default 
  //printf Displays data of different data types 
  printf(" My name is %s, My age is %d My lucky character is %c\n","Tony",28,'C');
}
1

Use the scanf function in conjunction with the regular expression scan to match the specified regular data


#include <stdio.h>
/*
   use printf Formatted output data 
  @author Tony 18601767221@163.com
  @since 20160530 09:14
*/
void printf_sample() {
// The output is eventually printed as a string 
  printf("Hello World \n");// Output string constants, which are output to the console by default 
  //printf Displays data of different data types 
  printf(" My name is %s, My age is %d My lucky character is %c\n","Tony",28,'C');
}
2

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: