Course Content#
Overview of C Language#
- Why learn C language?
Assembly Language | C Language (Compiled Language, High-Level Language) |
---|---|
Strongly dependent on hardware devices - registers | Portability |
Direct communication with registers, complex code, higher efficiency | Simple, readable, high development efficiency |
Example: Want to communicate with a foreigner | |
Learn English | Find a translator |
-
Importance of C
- C came first, then Linux
- The Unix operating system is paid, so Linux was developed by Linus
- The underlying implementation of Linux is in C
- Java, C++, Python are all based on C
PS: Mac OS is based on Unix
- C came first, then Linux
-
Learning logical thinking and programming paradigms
- Not just syntax
- C language supports only one: procedural programming
- C++ supports four: procedural, object-oriented, generic programming, functional programming
Input and Output Functions#
Analogous to human listening and speaking
- Output function: printf
Header File | stdio.h | |
---|---|---|
⭐Prototype | int printf(const char *format, ...); | Outputs are all characters |
Return Value, int, number of characters output successfully | '\n' is one character | |
Parameter 1, format, format control string | ||
Variable argument list, ... | Valid statement, can be compiled |
- Input function: scanf
Header File | stdio.h | |
---|---|---|
⭐Prototype | int scanf(const char *format, ...); | |
Return value, int, number of parameters read successfully | <0, invalid; ≥0, valid (including 0) | |
while(scanf(...) != EOF) | -1 <=> EOF (hidden file descriptor) |
- Keyboard input end-of-file (EOF):
-
- Unix: Ctrl+D
-
- Windows: Ctrl+Z
-
- You can also use Ctrl+C to interrupt the loop
C Language Documentation and Coding Standards#
-
Use Wikipedia to check functions
-
cpp reference authoritative documentation
- Refer to the Pirate Treasure official website
-
Coding standards (more code, more bugs) Google is the father
- Baidu + Google
- Alibaba + Google
- Reduce bug rate
-
Reference books (1 month is enough; this book is cross-disciplinary)
-
In-Class Exercises#
-
- Do not use while function, can directly use printf's return value
- printf() nesting
- Code

- %[^\n]s
// Purpose:
char str[100] ={0};
scanf("%s", str); // Encounters spaces and other delimiters will move to the next parameter assignment
scanf("%[^\n]s", str); // Can read spaces as characters, the s after [] is optional
|[]|Character matching set|
|:----:|:----|:----:|:----|
|^|Negation/Except|
|\n|Newline character|
- There will be issues when reading in a loop
while (scanf("%[^\n]s", str) != EOF) {
...
}
- Input Hello World, output will not stop, continuously outputting Hello World
- Because \n is treated as a delimiter moving to the next parameter assignment, but \n will not be consumed
- Refer to Kaikeba QA--C Language Course on October 13 regarding scanf issues: The reason it gets stuck on '\n' is that %[] cannot consume leading whitespace characters.
My understanding differs slightly from above
-
Displaying scanf's output shows that only the first successful read had 1 parameter, the rest are all 0
-
-
According to my understanding, if \n is negated in regex, it cannot be read in, but is treated as a delimiter, so it enters the output statement but cannot be read in, thus getting stuck in a loop;
-
Without regex, \n is treated as a delimiter and continues to read the next character, so it stops, but encounters a space and moves to the next parameter assignment.
-
-
Using getchar(), can consume one character, such as \n
- Printing the value of getchar() shows that \n is consumed, allowing the next line to be read
-
-
The red box shows the consumed character: \n, as seen in lines 15-20 of the code below
-
Perhaps it is also possible to read strings containing spaces by looping through char, using a two-dimensional character array, moving to the next line when encountering \n.
-
Another perspective to consider, refer to the issue with \n in scanf-CSDN
-
Code
-
Highlight Notes#
- scanf uses delimiters (spaces, newlines, etc.) to separate multiple variable inputs
- The precedence of assignment operators (=, -=, etc.) is very low (associativity: right to left), lower than the == operator
- The value of the expression formed by the assignment operator is the assigned value
int ret;
printf("%d\n", ret = 3);
// Outputs 3
-
./a.out > output can redirect output to the output file (overwriting the original file) without displaying it in the terminal
- > means standard output redirection
-
Basic vim operations can be practiced with vimtutor, see the document on Shimo -Common Commands in Linux: Vim
-
In printf() format control strings, if \n is not used, there is a % at the end
- This percent sign is added by the shell because you did not input a newline.
Think about if you didn't input a newline, shouldn't the shell's prompt follow your output (like hello world) directly, making it look messy?
- Note: Use %c with caution, it reads everything in
Code Demonstration#
printf Function#
Basic Knowledge of printf Family#
- printf: Print to standard output (stdout)
- sprintf: Print to string
- Can be used for string concatenation
- sprintf(str, "", ...);
- fprintf: Print to file
- First open the file, fopen: w for write, r for read, a for append
- Returns a pointer of type FILE
- fprintf(FILE pointer, "", ...);
- “...”: Reads the addresses of variable arguments
- The string variable itself passes its address
- First open the file, fopen: w for write, r for read, a for append

int main()
{
FILE* fp;
int i = 617;
char* s = "that is a good new";
fp = fopen("text.dat", "w");
fprintf(fp, "%d\n", i); // Just pass the variable name, no need to pass the address
fprintf(fp, "%s", s);
fclose(fp); // Remember to close the file with fclose
return 0;
}
Exercises#
- Based on the last three bits of n's binary value, add different types of brackets to str
-
-
n's definition is at the beginning of printf
-
Use macro definition to define the swap function
-
-
__typeof gets the variable type, directly used to declare the type of intermediate variables
-
Can the two parameters of sprintf not be the same?
- 💡 The names cannot be the same?
- If both parameters are str, see below:
- 💡 The names cannot be the same?
-
-
The result is as follows: the length of the value in () is the same as the original value, and the output content () seems to overwrite the original content
- Must use pointers to pass addresses?
- If using variables directly, it can be done, see below:
-
-
-
-
- But with multiple conditional judgments, think about whether it's easy to swap character arrays without using pointers?
- ❓Actually, the variable name of the character array represents the address of the character array, can the address be swapped directly? It failed, it should not work, after all, arrays cannot be easily moved, but pointers pointing to arrays can be moved.
- So still learn to use pointers~
- The FILE pointer of fprintf can also be stdout and stderr
- But with multiple conditional judgments, think about whether it's easy to swap character arrays without using pointers?
-
-
-
- The final output is as follows:
-
-
-
- What is the difference between stdout and stderr?
- You can use > to redirect standard output stdout, while stderr will not be redirected, see below:
- What is the difference between stdout and stderr?
-
⭐: You can view error information separately while suppressing a lot of normal output
-
-
-
- Similarly, you can also use 2> to redirect only error output, see below:
-
-
Additional Knowledge Points#
- File Descriptors
- stdin: Standard input
- stdout: Standard output
- stderr: Standard error output
- EOF: -1
- File Permissions
- Everything is a file in Linux~
- ls -al .: Can display file permissions
- rwx readable, writable, executable
- Three Common Methods for Array Initialization ({0}, memset, for loop assignment)-CSDN
Points to Consider#
- Why do parameters in scanf need to pass addresses?
- scanf needs to modify the values of parameters; if values are passed, it will not be able to change their values.