Bo2SS

Bo2SS

1 Introduction to Language Basics

Course Content#

Overview of C Language#

  • Why learn C language?
Assembly LanguageC Language (Compiled Language, High-Level Language)
Strongly dependent on hardware devices - registersPortability
Direct communication with registers, complex code, higher efficiencySimple, readable, high development efficiency
Example: Want to communicate with a foreigner
Learn EnglishFind 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
  • 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 Filestdio.h
⭐Prototypeint 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 Filestdio.h
⭐Prototypeint 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):
      1. Unix: Ctrl+D
      1. 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

  • 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)

    • Image

In-Class Exercises#

  • Image
  • Do not use while function, can directly use printf's return value
  • printf() nesting
  • Code
Image
  • Image
  1. %[^\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|

  1. 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
  1. Because \n is treated as a delimiter moving to the next parameter assignment, but \n will not be consumed

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

  • Image
  • 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.

  • Image
  1. 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
  • Image
  • 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

  • Image

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)

Image

  • 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
Image

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#

  1. Based on the last three bits of n's binary value, add different types of brackets to str
  • Image
  • n's definition is at the beginning of printf

  • Use macro definition to define the swap function

  • Image

  • __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:
  • Image
  • 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

    • Image
    • Must use pointers to pass addresses?
      • If using variables directly, it can be done, see below:
  • Image
      • 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
  • Image
      • The final output is as follows:
  • Image
      • What is the difference between stdout and stderr?
        • You can use > to redirect standard output stdout, while stderr will not be redirected, see below:
  • Image

​ ⭐: 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:
  • Image

Additional Knowledge Points#

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.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.