C language learning (2) string and formatted input/output

1. String

A string is a sequence of one or more characters. For example: "Hello World"

Double quotes are not part of the string. Just tells the compiler that it's enclosing a string, just as single quotes are used to denote single characters.

When double quotes are used to indicate a string, there will be a "\0" at the end of the string by default to indicate the end of the string. When a string is represented by a character array, if there is no "\0" at the end, the array is a character array.

#include <stdio.h>

int main() {
    
    

    // 双引号定义的字符串
    char ar1[] = "abc";
    // 字符数组定义的字符串。末尾的\0表示字符串的结束。如果没有\0则表示一个字符数组
    char ar2[] = {
    
    'a', 'b', 'c', '\0'};
    printf("%s\n",ar1);
    printf("%s\n",ar2);

    return 0;
}

#include <stdio.h>
#include <string.h>

int main() {
    
    

    // 双引号定义的字符串
    char ar1[] = "abc";
    // 字符数组定义的字符串。末尾的\0表示字符串的结束。如果没有\0则表示一个字符数组
    char ar2[] = {
    
    'a', 'b', 'c'};
    printf("%s\n",ar1);
    printf("%s\n",ar2);
    // strlen函数为统计字符串的长度,统计\0之前的字符。
    printf("%llu\n", strlen(ar1));
    // 输出随机值,直到遇到\0才会输出
    printf("%llu\n", strlen(ar2));

    return 0;
}

1.1 char type array and null character

The C language does not have a variable type dedicated to storing strings, and strings are stored in arrays of char type. The array is composed of continuous storage units, and the characters in the string are stored in adjacent storage units, and each storage unit stores a character.

insert image description here
The character "\0" at the position at the end of the array. Is the null character (null character), C language uses it to mark the end of the string. The null character is not the number 0, it is a non-printing character whose ASCII code value is 0.

Strings in C must be null-terminated, which means that the storage capacity of the array must be at least 1 more than the number of characters in the string to be stored. You can think of an array as a row of multiple storage units. More formally, an array is an ordered sequence of data elements of the same type.

char str[40];

The above program declares an array containing 40 storage units (or elements), and each storage unit stores a value of type char. The square brackets behind str indicate that this is an array, the number in the square brackets indicates the number of elements in the array, and the char indicates the type of each element.

1.2 Strings and characters

String constants (such as " X ") are different from character constants (' X '). One of the differences is that character constants are basic types (char), while strings are derived types (char arrays); the second difference is "X" Actually consists of two characters: 'X' and the null character \0.

Two, input

2.1 scanf () function

The C library contains several input functions, scanf() is the most general one because it can read data in different formats. scanf(), like printf(), also takes a format string and an argument list. The scanf() function uses pointers to variables (pointers will be explained in detail later).

Two rules for using scanf():

1、如果用scanf()读取基本变量类型的值,在变量名前加上一个 “&”。
2、如果使用scanf()把字符串读入字符数组中,不要使用 “&”。

2.2 Two usages

1、scanf("输入控制符",输入参数);
作用:将从键盘输入的字符转化为输入控制符所规定格式的数据,然后存入以输入参数的值为地址的变量中。
#include <stdio.h>

int main() {
    
    

	int num;

	printf("Please enter a number:\n");
	scanf_s("%d", &num);
	printf("输入的数字为:%d", num);

	return 0;

}
2、scanf("非输入控制符 输入控制符",输入参数);
作用:将从键盘输入的字符转化为输入控制符所规定格式的数据,然后存入以输入参数的值为地址的变量中,非输入控制符必须完全输入。
#include <stdio.h>

int main() {
    
    

	int num;

	printf("Please enter a number:\n");
	// ABC为非输入控制符,在进行输入时也必须加上ABC
	scanf_s("ABC%d", &num);
	printf("输入的数字为:%d", num);

	return 0;

}

3. Output

3.1 printf()

The instruction to request the printf() function to print data must match the type of the data to be printed. For example, %d is used to print integers, and %c is used to print characters. These symbols are called conversion specifications , and they specify how to convert the data into a displayable form.

3.1.1 Four usages of printf

1、printf("字符串")
#include <stdio.h>

int main() {
    
    

	// 输出字符串
	printf("Hello world");

	return 0;
}
2、printf("输出控制符",输出参数)
#include <stdio.h>

int main() {
    
    

	int num = 123;
	// 输出变量的值
	printf("%d",num);

	return 0;
}
3、printf("输出控制符1 输出控制符2 ...",输出参数1,输出参数2...)。输出控制符和输出参数必须对应。
#include <stdio.h>

int main() {
    
    

	int num = 123;
	char ch = 'A';
	// 输出变量的值
	printf("%d %c",num, ch);

	return 0;
}
4、printf("输出控制符 非输出控制符",输出参数)
#include <stdio.h>

int main() {
    
    

	int num = 123;
	char ch = 'A';
	// is char为非输出控制符
	printf("%d %c is char",num, ch);

	return 0;
}

3.1.2 Common output control characters

conversion instructions output
%a Floating point, hexadecimal, and p-notation (C99/C11)
%A Floating point, hexadecimal, and p-notation (C99/C11)
%c single character
%d signed decimal integer
%e Floating point number, e notation
%E Floating point number, e notation
%f floating point number, decimal notation
%g Automatically selects %f or %e, depending on the value. The %e format is used when the exponent is less than -4 or greater than or equal to the precision
%G Depending on the value, %F or %E is automatically selected. The %E format is used when the exponent is less than -4 or greater than or equal to the precision
%i signed decimal integer (same as %d)
%o unsigned octal integer
%p pointer
%s string
%u unsigned decimal integer
%x unsigned hexadecimal integer, use hexadecimal 0f
%X unsigned hexadecimal integer, use hexadecimal 0F
%% print a percent sign

3.1.3 Conversion specification modifiers for printf()

Insert modifiers between % and the conversion character to modify the basic conversion specification. The following two tables list the legal characters that can be used as modifiers. If you want to insert multiple characters, the writing order should be the same as the order of the modifiers in the table printf(), not all combinations are feasible. Some characters in the table are newly added by C99. If the compiler does not support C99, it may not support all the items in the table.

Modifiers for printf()

Modifier meaning
mark The printf() flag describes five flags (-, +, space, #, and 0), and can use no flags or multiple flags. Example: "%-10d"
number The minimum field width, if the field cannot accommodate the number or string to be printed, the system will use a wider field. Example: "%4d"
. number precision. For %e, %E and %f conversions, indicates the number of digits to the right of the decimal point. For %g and %G conversions, the maximum number of significant digits. For %s conversion, indicates the maximum number of characters to be printed. For integer conversions, the minimum number of digits to print a number. Use leading 0's to reach this number of digits if necessary. Just use . to mean followed by a 0, so %.f and %.0f are the same. Example: "%5.2f" prints a floating point number with a field width of 5 characters, with two digits after the decimal point.
h Used together with an integer conversion specification to represent a value of type short int or unsinged short int. Example: "%hu", "%6.4hd"
hh Used together with an integer conversion specification to represent a value of type singed char or unsinged char. Example: "%hhu", "%6.4hhd"
j Used with an integer conversion specification to represent a value of type intmax_t or uintmax_t, as defined in stdint.h. Example: "%jd", "%8jx"
l Used with an integer conversion specification to represent a value of type long int or unsinged long int. Examples: "%ld", "%8lu"
ll Used with an integer conversion specification to indicate a value of type long long int or unsinged long long int (C99). Examples: "%lld", "%6llu"
L Used together with the floating-point conversion specification to represent a value of type long double. Example: "%Ld", "%10.4Le"
t Used with an integer conversion specification, it represents a value of type ptrdiff_t. ptrdiff_t is the type for the difference of two pointers (C99). Examples: "%td", "%l2ti"
z Used together with an integer conversion specification to represent a value of type size_t. size_t is the type returned by sizeof (C99). Examples: "%zd", "%l2zd"

Tokens in printf()

Modifier meaning
- The item to be printed is left aligned. That is, the item is printed starting from the left of the field. Example: "%-10s"
+ Signed values ​​display a plus sign in front of the value if they are positive, and a minus sign in front of the value if they are negative. Example: "%+6.2f"
space A signed value displays a leading space (no characters) before the value if it is positive, or a minus sign + sign overlaying a space before the value if it is negative. Example: "%6.2f"
# Transform the result into another form. If it is in %o format, it starts with 0; if it is in %x or %X format, it starts with 0x or 0X; for all floating-point number formats, # ensures that a decimal point character is printed even if there is no number behind it. For %g and %G formats, # prevents trailing 0s from being removed from the result. Examples: "%#o", "%8.0f", "%+#10.3e"
0 For numeric formats, pad the field width with leading 0s instead of spaces. For integer formats, the - flag, if present or specifying a precision, is ignored
#include <stdio.h>

#define PAGE 668
int main() {
    
    


    printf("*%d*\n", PAGE);
    printf("*%2d*\n", PAGE);
    printf("*%10d*\n", PAGE);
    printf("*%-10d*\n", PAGE);
    return 0;
}

输出结果:
*668*
*668*
*       668*
*668       *
#include <stdio.h>

#define PAGE 3852.99
int main() {
    
    


    printf("*%f*\n", PAGE);
    printf("*%e*\n", PAGE);
    printf("*%4.2f*\n", PAGE);
    printf("*%3.1f*\n", PAGE);
    printf("*%10.3f*\n", PAGE);
    printf("*%10.3E*\n", PAGE);
    printf("*%+4.2f*\n", PAGE);
    printf("*%010.2f*\n", PAGE);
    return 0;
}
输出结果:
*3852.990000*
*3.852990e+03*
*3852.99*
*3853.0*
*  3852.990*
* 3.853E+03*
*+3852.99*
*0003852.99*

3.1.4 Why output control characters are needed

1、0和1组成的代码可以表示数据也可以表示指令。
2、如果0和1组成的代码表示的是数据的话,那么同样的0和1代码组合以不同的输出格式输出就会有不同的输出结果。

Guess you like

Origin blog.csdn.net/qq_46292926/article/details/127550588