Before We Start: Why Engage with Code?
Why Learn Programming? (Not Just to Look Cool)
In this digital age, programming is like a “magic wand” of the new era! It not only powers those cool tech gadgets but also quietly infiltrates the corners of our lives. Think about it, mobile apps, websites, games, and even your smart fridge all have code working behind the scenes. Mastering programming is like getting a VIP ticket to the future job market.
For you personally, learning programming can exercise your brain, enhance your problem-solving “combat power,” and cultivate the legendary “logical thinking” and “innovation ability.” Don’t think programming is just about monotonously typing on a keyboard; it’s actually an art of breaking down complex problems into smaller steps. Moreover, knowing a bit of programming can make you seem particularly “tech-savvy” when discussing computers with others.
For society as a whole, programming is the “accelerator” of technological advancement and the “lubricant” of social development. Developing new software and optimizing old systems all rely on the “magic touch” of programmers. From healthcare to finance, from education to entertainment, programming skills are like a universal remedy, needed everywhere.
Don’t believe it? Look at this piece of C++ code below; it’s like a magic spell that makes the computer obediently print a greeting. This is just the beginning, but taking this step puts you on the path to becoming a “wizard!”
#include <iostream> // Include the "spell library" to perform the "output magic"
int main() { // This is the "main ritual," where all magic begins
// Shout at the console: "Welcome to the world of programming!"
std::cout << "欢迎来到编程的世界!";
return 0; // The ritual ends successfully, returning a signal of "all is well"
}
Did you understand? <span>#include <iostream></span> is summoning the “spirit of input and output,” <span>int main()</span> is our “main battlefield,” and <span>std::cout << ...</span> is the specific “casting” action. Isn’t it simple? Keep practicing, and you’ll find yourself enjoying it more and more, with confidence soaring!
Why C++? (Because It’s Fast and Powerful)
C++ is a “big brother” in the programming world, capable of being as elegant as high-level languages while directly manipulating hardware like low-level languages; it’s truly “versatile.” Why do I recommend starting with it?
-
Extensive Applications: Game development (think of those addictive blockbusters), operating systems, browsers, databases, smart devices… C++ is everywhere. Learning it opens up a dizzying array of job options.
-
Lightning-Fast Performance: C++ allows you to directly “play” with memory, writing highly efficient code. This is a “nuclear weapon” level capability for scenarios requiring high performance, such as real-time systems and big data processing.
-
Object-Oriented “Tricks”: C++ supports classes, inheritance, and polymorphism, helping you write modular and reusable code, bidding farewell to “spaghetti programming.”
-
Large “Support Team”: C++ has a massive developer community. Encounter a problem? Just search online, and you’ll find tutorials, experts, and solutions galore; you’re not fighting alone!
-
Keeping Up with the Times, Growing More Powerful: Don’t be fooled by C++’s age; it has been continuously updated. Since C++11, new features like smart pointers and lambda expressions have been introduced, making programming simpler, safer, and trendier.
Check out this small example from C++11, using <span>auto</span> and lambda expressions, making the code instantly “high-end”:
#include <iostream>
#include <vector> // Include the vector container, which can hold many items
int main() {
// Use auto to let the compiler guess the type, a blessing for the lazy!
std::vector<int> numbers = {1, 2, 3, 4, 5};
auto sum = 0; // Compiler: Hmm, I know this is an integer
// Elegantly traverse and sum using a lambda expression, the code is incredibly concise
for (auto number : numbers) { // Range for loop, iterating through each number
sum += number; // Accumulate
}
std::cout << "元素总和: " << sum << std::endl; // Output result
return 0;
}
See? <span>auto</span> saves you from writing types, and lambda makes operations in loops more compact. C++ is constantly striving to be more user-friendly!
Who Is This Tutorial For? (Attention Programming Novices!)
This tutorial is tailored for you—those curious about programming, especially those wanting to get started with C++! Whether you are a computer science student or just someone looking to light up a new skill tree, you are welcome aboard. If you have previously encountered languages like Python or Java, congratulations, you already have a “foundation”; learning C++ will be smoother since many basic concepts are common (like variables and loops, those old friends).
Before we start, please fasten your seatbelt and maintain an open and curious mind. C++ is powerful, capable of handling everything from simple command-line tools to complex graphical interface programs. Following this tutorial, you will gradually master the basic syntax of C++ and be able to write your first (perhaps a bit rudimentary but significant) small program.
To give you a taste, let’s start with a traditional programming task—printing “Hello, World!”:
#include <iostream> // Once again, summon the input-output "spirit"
int main() { // The "heart" of the program
// Let the computer greet the world!
std::cout << "Hello, World!" << std::endl; // std::endl indicates a new line, very formal!
return 0; // Tell the system: the program ran successfully!
}
<span>#include <iostream></span> includes the standard library, <span>main()</span> is the starting point, <span>std::cout</span> is responsible for output, and <span>std::endl</span> is responsible for line breaks. Simple, right? Are you ready? Let’s officially set off!
Preparation Before Getting Started: Sharpening the Axe Saves Time
Step 1: Choose a Handy “Weapon”—IDE (like VS Code)
Choosing a good Integrated Development Environment (IDE) is like selecting a trusty weapon; it can make your programming journey much more efficient. I highly recommend Visual Studio Code (VS Code); it’s lightweight, powerful, and rich in plugins, and best of all, it’s free!
Go to the VS Code official website to download the installer, and just click “Next” all the way through. Once installed, open it; the interface is clean and refreshing, making it very suitable for beginners.
Having just an editor isn’t enough; you need to install the C++ “plugin”:
- Click the icon on the left that looks like building blocks (the extensions view), or simply press
<span>Ctrl+Shift+X</span>. - Type “C++” in the search box.
- Find the official “C/C++” extension from Microsoft and click “Install.”
Done! Now your VS Code is armed and ready to start writing C++ code. For example, type in the previous “Hello World” code:
#include <iostream> // Include the input-output stream library
int main() {
std::cout << "Hello, World!" << std::endl; // Output Hello, World!
return 0;
}
Save this code as a <span>.cpp</span> file (for example, <span>hello.cpp</span>). Next, you need to configure the compiler so that VS Code knows how to turn your code into an executable file. You can refer to the official VS Code documentation or search for related tutorials; it’s just a matter of a little setup.
With VS Code, writing code and debugging becomes much easier!
Step 2: Invite a “Translator”—Install a Compiler (like GCC)
Just writing code isn’t enough; the computer doesn’t understand our “human language” (C++ code). We need a “translator”—a compiler—to convert C++ code into a language the computer can understand (machine code). GCC (GNU Compiler Collection) is an excellent and free “translator.”
For Windows:
It’s recommended to use MinGW or MSYS2 to install GCC.
- Go to the MinGW or MSYS2 official website to download the installer.
- Run the installer and follow the prompts.
- After installation, remember to set the environment variables so you can directly call
<span>g++</span><span> in the command line.</span>
For macOS:
Using Homebrew is the easiest.
- Open the “Terminal.”
- If you haven’t installed Homebrew, run the command to install it:
- Install GCC using Homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install gcc
For Linux:
Most Linux distributions either come with GCC pre-installed or can easily install it using a package manager. For example, on Ubuntu:
sudo apt update
sudo apt install g++
Check if it’s installed:
Open the command line (CMD or PowerShell for Windows, Terminal for macOS/Linux) and type:
g++ --version
If you see the version information, congratulations, the compiler is ready!
Try It Out:
Write a simple C++ code and save it as <span>hello.cpp</span><span>:</span>
#include <iostream>
int main() {
std::cout << "Hello, C++! Compiler is working!" << std::endl;
return 0;
}
In the command line, switch to the directory where <span>hello.cpp</span><span> is located, then execute:</span>
g++ hello.cpp -o hello # Compile the code, generating an executable file named hello
./hello # Run this file (it might be hello.exe on Windows)
If the screen displays “Hello, C++! Compiler is working!”, then perfect! The preparation work is complete, and you can officially start coding!
Step 3: Your First C++ Program—”Hello World”
The Classic: Hello World Example
Learning any programming language involves printing “Hello World.” It’s like the “beginner’s quest” in the programming world—simple yet significant.
#include <iostream> // Include the standard input-output "toolkit"
int main() { // Main function, the "start button" of the program
// Let the computer greet the world
std::cout << "Hello, World!" << std::endl; // Output this string and then move to a new line
return 0; // Tell the operating system: "Task completed, all OK!"
}
Code Explanation:
<span>#include <iostream></span>: Tells the compiler: “I want to use input-output functionality, quickly bring me the corresponding toolkit!”<span>int main()</span>: Every C++ program starts running from the<span>main</span>function.<span>int</span>indicates that this function will return an integer upon completion.<span>std::cout</span>: Can be understood as the “standard output stream,” usually referring to your screen.<span><<</span>is a “transfer” symbol that passes the right-hand side to the left-hand side<span>std::cout</span>.<span>"Hello, World!"</span>: This is the text content to be output, enclosed in double quotes.<span>std::endl</span>: Outputs a newline character and clears the buffer (don’t worry about what that is, just know it’s a new line).<span>return 0;</span>: The program has finished running, returning 0, indicating everything is normal. If it returns another number, it usually indicates a problem.
Does it feel a bit clearer now?
From Code to Execution: Compilation and Running
Once you’ve written the code (<span>.cpp</span> file), how do you get it to run? It involves two steps: compilation and execution.
Compilation: Turning Code into Magic
Use the compiler we installed earlier (like <span>g++</span><span>) to "cast the spell":</span>
g++ hello.cpp -o hello
<span>g++</span>: Summons the compiler.<span>hello.cpp</span>: The source code file you want to compile.<span>-o hello</span>: Tells the compiler that the executable file generated after successful compilation will be named<span>hello</span>(Windows will automatically add the<span>.exe</span>suffix).
If there are no errors in the code, the compiler will “magically” produce a file named <span>hello</span> (or <span>hello.exe</span>).
Execution: Witnessing the Moment of Magic
In the command line, type:
./hello # Linux/macOS
# or
hello.exe # Windows
Press Enter, and if all goes well, you should see on the screen:
Hello, World!
Congratulations! You have successfully run your first C++ program! Although simple, this is the first step of a long journey. Next, we will delve deeper into more syntax!
C++ Basic Syntax: The Bricks and Tiles of Building a House
Comments: Adding Some “Inner Thoughts” to the Code
Comments are for programmers (including your future self) to read; the compiler will ignore them. Good comments can make the code easier to understand.
Short Comment: Single-Line Comment <span>//</span>
Start with two slashes <span>//</span>; everything from <span>//</span> to the end of the line is a comment. Suitable for brief explanations.
#include <iostream> // Include the input-output library, this line is a comment
int main() {
// The following line of code will print a sentence
std::cout << "Hello, World!"; // This is also a comment, explaining what this line does
return 0; // Program ends, returns 0, comment explaining
}
Long Comment: Multi-Line Comment <span>/* ... */</span>
Start with <span>/*</span> and end with <span>*/</span>; you can write many lines in between. Suitable for detailed explanations or temporarily “sealing” a block of code.
#include <iostream>
int main() {
/*
Here you can write a long comment,
explaining what this program does,
or recording some thoughts.
Compiler: I see nothing~
*/
std::cout << "Hello, World!" << std::endl;
/*
// For example, if you don’t want to run the line below for now, you can comment it out
std::cout << "This line of code is temporarily sealed!" << std::endl;
*/
return 0;
}
Note: Multi-line comments cannot be nested! Like this <span>/* ... /* ... */ ... */</span> is not allowed and will cause an error.
The Basic Skeleton of a Program
The Main Character: Main Function <span>main()</span>
Every C++ program must have a <span>main()</span> function; it is the entry point of the program, and the code starts executing from here. We usually write it as <span>int main()</span>, indicating that it will return an integer upon completion (usually 0 indicates success).
#include <iostream> // Need to use output functionality, so include it
int main() { // This is the main function, the starting point of the program
// Write the main logic code here
std::cout << "程序开始运行啦!" << std::endl;
// ... other code ...
return 0; // Program ends normally, returns 0
}
<span>main</span> function can also accept parameters passed from the command line, but that’s a bit advanced; we’ll just acknowledge that it exists for now.
Summoning Helpers: Including Header Files <span>#include</span>
When writing code, we often need to use functionalities that others have already written, which are usually placed in “header files.” You can summon these header files into your code using the <span>#include</span> directive.
- Standard Library Header Files: Enclosed in angle brackets
<span><></span>, for example,<span><iostream></span>. The compiler will look for them in system-specified locations.#include <iostream> // Summon the standard input-output library #include <vector> // Summon the vector container library - Custom Header Files: Enclosed in double quotes
<span>""</span>, for example,<span>"myheader.h"</span>. The compiler will first look in the current directory, and if not found, it will look in system-specified locations.#include "my_functions.h" // Summon the functionality I wrote myself
To prevent the same header file from being summoned multiple times, causing confusion, header files usually use a technique called “include guards”:
// my_functions.h
#ifndef MY_FUNCTIONS_H // If this macro has not been defined...
#define MY_FUNCTIONS_H // ...then define it
// Here is the content of the header file, such as function declarations
void doSomethingCool();
#endif // MY_FUNCTIONS_H // End of conditional compilation
This way, even if you accidentally <span>#include</span> it twice, the second time will be skipped because <span>MY_FUNCTIONS_H</span> has already been defined.
Data Types: Giving Data a Home
Basic Types: Common Data Types
Integer House: <span>int</span>
<span>int</span> is used to store integers (numbers without decimal points), including positive numbers, negative numbers, and zero. It typically occupies 4 bytes of memory (depending on the system).
#include <iostream>
int main() {
int age = 18; // Declare an integer variable named age and assign it the value 18
int temperature = -5; // It can also be negative
int count = 0; // Zero is also fine
std::cout << "年龄: " << age << std::endl;
age = age + 1; // You can perform operations on it
std::cout << "明年就 " << age << " 岁了" << std::endl;
return 0;
}
If <span>int</span> is not large enough, there are also <span>long int</span> and <span>long long int</span> these “luxury version” integer types.
Decimal Mansion: <span>float</span>, <span>double</span>
If you need to represent numbers with decimal points, use <span>float</span> or <span>double</span>.
<span>float</span>: Single-precision floating-point number, not very precise (about 6-7 significant digits), occupies less memory (usually 4 bytes).<span>double</span>: Double-precision floating-point number, highly precise (about 15 significant digits), occupies more memory (usually 8 bytes). Generally, it’s recommended to use<span>double</span>, unless you are particularly stingy with memory.
#include <iostream>
#include <iomanip> // Including this library allows controlling output format
int main() {
float price = 9.9f; // Note: It’s best to add an f or F after float constants
double pi = 3.1415926535;
std::cout << "价格: " << price << std::endl;
// Set output precision to see how precise double can be
std::cout << "圆周率: " << std::fixed << std::setprecision(10) << pi << std::endl;
return 0;
}
Note: Computers may not store decimals precisely, so be careful when comparing two floating-point numbers for equality; you can’t just use <span>==</span>; usually, you check if their difference is within a very small range.
Character Cottage: <span>char</span>
<span>char</span> is used to store a single character, such as a letter, number, or symbol. It typically occupies only 1 byte. Character constants should be enclosed in single quotes <span>'</span>.
#include <iostream>
int main() {
char grade = 'A'; // Store a letter
char symbol = '$'; // Store a symbol
char digit = '7'; // Store a digit character
std::cout << "成绩: " << grade << std::endl;
std::cout << "符号: " << symbol << std::endl;
// char actually stores numbers (ASCII codes)
int asciiValue = grade; // Can directly convert to an integer to see its ASCII code
std::cout << "A 的 ASCII 码是: " << asciiValue << std::endl; // Outputs 65
// Special characters are escaped with a backslash \
char newline = '\n'; // Newline character
std::cout << "第一行" << newline << "第二行" << std::endl;
return 0;
}
Settling Down: Variable Declaration and Initialization
First, Reserve a Spot: Variable Definition
Defining a variable means telling the compiler: “I want a piece of memory to store a certain type of data, and I’ll name it xxx.”
int studentCount; // Define an integer variable named studentCount
double averageScore; // Define a double-precision floating-point variable
char initialLetter; // Define a character variable
You can only use a variable after defining it.
Grand Opening: Variable Initialization
Initialization means giving a variable an initial value at the time of definition. This is a good habit to avoid using some inexplicable “garbage values.”
// Direct initialization (using the equals sign =)
int year = 2024;
float discount = 0.8f;
char initial = 'L';
// Constructor initialization (looks like a function call, unique to C++)
int quantity(100);
double length(1.88);
// Uniform initialization (recommended in C++11 and later, using curly braces {})
int items{50};
double price{}; // Initialized to 0 or the zero value of the corresponding type
std::string name{"Alice"}; // Strings can also be initialized this way
// Constants must be initialized at the time of definition because their values cannot change
const double PI = 3.14159;
// PI = 3.14; // This line will cause an error! Constants cannot be changed
It’s recommended to use uniform initialization <span>{}</span>; it’s more versatile and can prevent certain unexpected type conversions.
Operators: The Addition, Subtraction, Multiplication, and Division of Code
Math Class Representative: Arithmetic Operators
These are the familiar addition <span>+</span>, subtraction <span>-</span>, multiplication <span>*</span>, division <span>/</span>, and modulus (remainder) <span>%</span>.
#include <iostream>
int main() {
int a = 10, b = 3;
std::cout << "a + b = " << a + b << std::endl; // 13
std::cout << "a - b = " << a - b << std::endl; // 7
std::cout << "a * b = " << a * b << std::endl; // 30
// Note that integer division results in an integer, the decimal part is simply discarded
std::cout << "a / b = " << a / b << std::endl; // 3 (not 3.333...)
// If you want an accurate result, at least one number must be a floating-point number
double result = (double)a / b; // Force a to be converted to double
std::cout << "精确的 a / b = " << result << std::endl; // 3.333...
// Modulus operation, finding the remainder, can only be used with integers
std::cout << "a % b = " << a % b << std::endl; // 1 (10 divided by 3 leaves a remainder of 1)
return 0;
}
Assignment Expert: Assignment Operators
The most basic is <span>=</span>, which assigns the value on the right to the variable on the left. There are also some compound assignment operators that make it more concise to write.
#include <iostream>
int main() {
int score = 0;
score = 100; // Basic assignment
int count = 5;
count += 3; // Equivalent to count = count + 3; now count is 8
std::cout << "count += 3: " << count << std::endl;
count -= 2; // Equivalent to count = count - 2; now count is 6
std::cout << "count -= 2: " << count << std::endl;
count *= 10; // Equivalent to count = count * 10; now count is 60
std::cout << "count *= 10: " << count << std::endl;
count /= 5; // Equivalent to count = count / 5; now count is 12
std::cout << "count /= 5: " << count << std::endl;
count %= 7; // Equivalent to count = count % 7; now count is 5 (12 divided by 7 leaves a remainder of 5)
std::cout << "count %= 7: " << count << std::endl;
return 0;
}
Using compound operators makes the code shorter and sometimes clearer.
Fair Judge: Comparison Operators
Used to compare the size of two values or whether they are equal, resulting in a boolean value <span>true</span> (true) or <span>false</span> (false).
<span>==</span>equals (note it’s two equal signs!)<span>!=</span>not equal<span><</span>less than<span>></span>greater than<span><=</span>less than or equal to<span>>=</span>greater than or equal to
#include <iostream>
int main() {
int x = 10, y = 20;
bool isEqual = (x == y); // false
bool isNotEqual = (x != y); // true
bool isLess = (x < y); // true
bool isGreater = (x > y); // false
bool isLessOrEqual = (x <= 10); // true
bool isGreaterOrEqual = (y >= 20); // true
std::cout << std::boolalpha; // Make bool values output true/false instead of 1/0
std::cout << "x == y: " << isEqual << std::endl;
std::cout << "x != y: " << isNotEqual << std::endl;
std::cout << "x < y: " << isLess << std::endl;
std::cout << "x > y: " << isGreater << std::endl;
std::cout << "x <= 10: " << isLessOrEqual << std::endl;
std::cout << "y >= 20: " << isGreaterOrEqual << std::endl;
return 0;
}
Comparison operators are the soul of <span>if</span> statements and loops.
Logic Master: Logical Operators
Used to combine multiple boolean expressions for “and,” “or,” and “not” judgments.
<span>&&</span>logical AND: Both sides must be<span>true</span>for the result to be<span>true</span>.<span>||</span>logical OR: As long as one side is<span>true</span>, the result is<span>true</span>.<span>!</span>logical NOT: Turns<span>true</span>into<span>false</span>and vice versa.
#include <iostream>
int main() {
int age = 25;
bool hasLicense = true;
bool isWeekend = false;
// Condition 1: Age greater than 18 AND has a license
bool canDrive = (age > 18) && hasLicense; // true && true -> true
// Condition 2: Age less than 12 OR it’s the weekend
bool canPlayOutside = (age < 12) || isWeekend; // false || false -> false
// Condition 3: Not the weekend
bool isWorkday = !isWeekend; // !false -> true
std::cout << std::boolalpha;
std::cout << "可以开车吗? " << canDrive << std::endl;
std::cout << "可以出去玩吗? " << canPlayOutside << std::endl;
std::cout << "是工作日吗? " << isWorkday << std::endl;
return 0;
}
Logical operators allow us to construct more complex conditional statements.
Interacting with the World: Input and Output
<span>cout</span>: Letting the Program Speak
<span>cout</span> (pronounced “see-out”) is the object responsible for output in the C++ standard library, usually outputting to the screen (console). You need to include the <span><iostream></span> header file and use it with the insertion operator <span><<</span>.
Basic Usage: Outputting Text and Variables
#include <iostream>
#include <string> // Include this for string type
int main() {
std::string name = "小明";
int score = 95;
// Output fixed text
std::cout << "大家好!";
// Output a new line (using std::endl)
std::cout << std::endl;
// Output the value of variables
std::cout << "姓名: " << name << std::endl;
std::cout << "分数: " << score << std::endl;
// You can output multiple things in sequence
std::cout << name << "考了" << score << "分,真棒!" << std::endl;
return 0;
}
<span>std::endl</span> not only creates a new line but also flushes the buffer, ensuring the content is displayed immediately. If you just want a new line, you can also use the <span>\n</span> character, which is slightly more efficient:<span>std::cout << "换行\n";</span>
A Bit More Advanced: Formatting Output
Sometimes you want to control the output format, such as decimal places, alignment, etc., which requires including the <span><iomanip></span> header file.
#include <iostream>
#include <iomanip> // Include formatting tools
#include <string>
int main() {
double pi = 3.14159265;
int number = 123;
std::string text = "C++";
// Control decimal places
std::cout << "圆周率 (保留2位小数): " << std::fixed << std::setprecision(2) << pi << std::endl;
// std::fixed indicates fixed decimal place display
// Control output width and alignment
std::cout << "数字 (宽度10,右对齐): |" << std::setw(10) << std::right << number << "|" << std::endl;
std::cout << "文本 (宽度10,左对齐): |" << std::setw(10) << std::left << text << "|" << std::endl;
// std::setw only affects the next output
// Restore default settings (if needed)
std::cout << std::resetiosflags(std::ios::fixed | std::ios::right | std::ios::left);
std::cout << std::setprecision(6); // Restore default precision
return 0;
}
<span>iomanip</span> tools can make your output neater and more professional.
<span>cin</span>: Listening to What Users Want to Say
<span>cin</span> (pronounced “see-in”) is the object responsible for reading data from standard input (usually the keyboard). It also requires the <span><iostream></span> header and is used with the extraction operator <span>>></span>.
Basic Usage: Reading User Input
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
// Prompt the user for input
std::cout << "请输入你的姓名: ";
// Read the user input string and store it in the name variable
std::cin >> name; // Note: cin stops reading at spaces or newlines
std::cout << "请输入你的年龄: ";
// Read the user input integer and store it in the age variable
std::cin >> age;
// Output the information read
std::cout << "你好, " << name << "! 你今年 " << age << " 岁了。" << std::endl;
return 0;
}
Important Note: <span>cin</span> stops reading strings at spaces, tabs, or newline characters. So if the user inputs “Li Lei,” <span>cin >> name;</span> will only read “Li.”
Reading a Whole Line: <span>getline</span>
If you want to read an entire line of input that includes spaces, you need to use the <span>getline</span> function.
#include <iostream>
#include <string>
int main() {
std::string fullName;
int age;
std::cout << "请输入你的年龄: ";
std::cin >> age;
// **Key Point**: Usually, you need to clear the newline character in the input buffer after cin >> and before getline
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// The above line means: ignore all characters in the buffer until a newline character is encountered
std::cout << "请输入你的全名: ";
std::getline(std::cin, fullName); // Read an entire line until the user presses Enter
std::cout << "你好, " << fullName << "! 你今年 " << age << " 岁了。" << std::endl;
return 0;
}
Remember that when mixing <span>cin >></span> and <span>getline</span>, you need to add <span>cin.ignore()</span> to clear the buffer; otherwise, <span>getline</span> may read the leftover newline character from the previous <span>cin >></span>, causing it to miss the content you want.
Input Can Also Go Wrong: Error Handling
If the user doesn’t follow the rules, for example, if you ask them to input a number and they input letters instead, <span>cin</span> will enter an “error state.” We can check this state and handle it.
#include <iostream>
#include <limits> // Need to use numeric_limits
int main() {
int number;
std::cout << "请输入一个整数: ";
// Loop until the user inputs a valid integer
while (!(std::cin >> number)) { // If reading fails...
std::cout << "输入无效,请输入一个整数: ";
std::cin.clear(); // Clear cin's error state flag
// Ignore the erroneous content in the buffer until a newline character is encountered
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "你输入的数字是: " << number << std::endl;
return 0;
}
By writing it this way, the program becomes more robust and less likely to crash due to user “mischief.”
Controlling Program Flow: Making Code “Alive”
Conditional Judgments: Which Path to Take?
<span>if</span> Statement: If… Then…
The most basic conditional judgment. If the condition after <span>if</span> is <span>true</span>, the code inside the curly braces <span>{}</span> will be executed.
#include <iostream>
int main() {
int temperature = 35;
if (temperature > 30) { // If the temperature is greater than 30 degrees...
std::cout << "天气太热了,开空调!" << std::endl; // ...then execute this line
}
std::cout << "程序继续执行..." << std::endl;
return 0;
}
<span>if...else</span> Statement: Two Choices
If the <span>if</span> condition is <span>true</span>, execute the <span>if</span> block; otherwise (<span>false</span>), execute the <span>else</span> block.
#include <iostream>
int main() {
int score = 55;
if (score >= 60) { // If the score passes...
std::cout << "恭喜,及格了!" << std::endl;
} else { // Otherwise...
std::cout << "很遗憾,没及格,下次努力!" << std::endl;
}
return 0;
}
if…else if…else
You can chain multiple <span>else if</span> statements to check multiple conditions, ending with an optional <span>else</span> to handle all other cases.
#include <iostream>
int main() {
int grade = 85;
if (grade >= 90) {
std::cout << "优秀 (A)" << std::endl;
} else if (grade >= 80) { // If not 90, check if it’s greater than or equal to 80
std::cout << "良好 (B)" << std::endl;
} else if (grade >= 70) { // If not 80, check if it’s greater than or equal to 70
std::cout << "中等 (C)" << std::endl;
} else if (grade >= 60) { // If not 70, check if it’s greater than or equal to 60
std::cout << "及格 (D)" << std::endl;
} else { // If none of the above conditions are met
std::cout << "不及格 (F)" << std::endl;
}
return 0;
}
The program will check conditions from top to bottom; once it finds a match, it executes the corresponding code block and exits the entire <span>if...else if...else</span> structure.
<span>switch</span> Statement: The Expert in Value Judgments
<span>switch</span> is specifically used to choose which case branch to execute based on the value of an integer or character type expression. It’s clearer than writing a long series of <span>if (x == ...)</span> statements.
#include <iostream>
int main() {
char level = 'B';
switch (level) { // Check the value of level
case 'A': // If level is 'A'
std::cout << "优秀!" << std::endl;
break; // **Important**: Jump out of switch after executing this case
case 'B': // If level is 'B'
std::cout << "良好!" << std::endl;
break;
case 'C': // If level is 'C'
std::cout << "中等。" << std::endl;
break;
case 'D': // If level is 'D'
std::cout << "及格。" << std::endl;
break;
default: // If none of the above cases match
std::cout << "不及格或无效等级。" << std::endl;
// The default branch usually doesn’t need a break because it’s already the last one
}
return 0;
}
Key Points:
<span>switch</span>must have an expression in parentheses that results in an integer or character.- Each
<span>case</span>is followed by a constant value and a colon<span>:</span>. <span>break;</span>is very important! If omitted, the program will continue executing the next<span>case</span>code (this is called “fall-through,” which is usually not what we want).<span>default</span>branch is optional and is used to handle all cases not explicitly listed.
Loop Structures: Letting the Computer Handle Repetitive Tasks
<span>for</span> Loop: Use It When the Number of Iterations is Known
<span>for</span> loops are best used when the number of iterations is known or there is a clear range. Its structure is compact:
for (initialization; condition; update) {
// Loop body: Code that repeats while the condition is true
}
- Initialization: Executed once before the loop starts, usually used to set the counter.
- Condition: Checked before each loop starts; if
<span>true</span>, it continues; if<span>false</span>, it ends the loop. - Update: Executed after each loop body, usually used to change the counter.
#include <iostream>
int main() {
// Print 0 to 4
std::cout << "打印 0 到 4: ";
for (int i = 0; i < 5; ++i) { // Initialize i=0; condition i<5; increment i by 1 after each loop
std::cout << i << " ";
}
std::cout << std::endl;
// Count down from 5 to 1
std::cout << "倒数 5 到 1: ";
for (int j = 5; j >= 1; --j) { // Initialize j=5; condition j>=1; decrement j by 1 after each loop
std::cout << j << " ";
}
std::cout << std::endl;
// C++11 range for loop (more concise, used for iterating over containers or arrays)
std::cout << "遍历数组: ";
int numbers[] = {10, 20, 30, 40, 50};
for (int num : numbers) { // Take each element from numbers and assign it to num
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
<span>while</span> Loop: Keep Doing While the Condition is Met
<span>while</span> loops are used when the number of iterations is uncertain but the condition for continuing the loop is known. It checks the condition first; the loop body is executed only if the condition is met.
#include <iostream>
int main() {
int count = 0;
// Loop while count is less than 3
while (count < 3) {
std::cout << "当前 count 是: " << count << std::endl;
count++; // Change the condition variable to give the loop a chance to end
}
std::cout << "循环结束,最终 count 是: " << count << std::endl;
// Simulate user inputting a password until correct
std::string password;
while (password != "123456") { // As long as the password is not "123456," keep looping
std::cout << "请输入密码: ";
std::cin >> password;
if (password != "123456") {
std::cout << "密码错误,请重试!" << std::endl;
}
}
std::cout << "密码正确,欢迎!" << std::endl;
return 0;
}
<span>do-while</span> Loop: Execute Once Before Saying Anything
<span>do-while</span> loops are very similar to <span>while</span> loops, but they execute the loop body once first, then check the condition. Therefore, regardless of whether the condition is initially met, the loop body will always execute at least once.
#include <iostream>
#include <string>
int main() {
char choice;
// At least execute the menu once, then decide whether to continue based on user choice
do {
std::cout << "\n--- 菜单 ---" << std::endl;
std::cout << "1. 开始游戏" << std::endl;
std::cout << "2. 加载存档" << std::endl;
std::cout << "Q. 退出" << std::endl;
std::cout << "请输入选项: ";
std::cin >> choice;
switch (choice) {
case '1': std::cout << "开始新游戏..." << std::endl; break;
case '2': std::cout << "加载存档中..." << std::endl; break;
case 'Q': std::cout << "正在退出..." << std::endl; break;
default: std::cout << "无效选项,请重新输入。" << std::endl;
}
// As long as the user input is not 'Q' or 'q', continue displaying the menu
} while (choice != 'Q' && choice != 'q');
std::cout << "感谢游玩!" << std::endl;
return 0;
}
<span>do-while</span> is suitable for scenarios where you need to perform an operation first and then decide whether to repeat, such as menu selection.
Journey Break: Summary and Outlook
Review of This Journey: What Skills Have You Acquired?
Congratulations on completing the first segment of your C++ journey! Together, we explored:
-
First Experience with Programming: You wrote the classic “Hello, World!” and felt the joy of making the computer speak.
// You can already understand and write this! #include <iostream> int main() { std::cout << "Hello, C++!" << std::endl; return 0; } -
Basic Skeleton of C++: You learned about the
<span>main</span>function,<span>#include</span>header files, comments, and other basic components. -
Data Types and Variables: You got to know
<span>int</span>,<span>float</span>,<span>double</span>,<span>char</span>—these “rooms” for giving data a home, and learned how to define and initialize variables.int age = 18; // Integer double price = 99.8; // Decimal char initial = 'L'; // Character const float PI = 3.14f; // Constant -
Operators: You mastered addition, subtraction, multiplication, and division (
<span>+ - * / %</span>), assignment (<span>= += -= *= /= %=</span>), comparison (<span>== != < > <= >=</span>), and logical (<span>&& || !</span>) operators—these “magic runes” that make the code come alive.int sum = 5 + 3; bool isReady = (sum > 7) && (initial == 'L'); -
Input and Output: You learned to use
<span>std::cout</span>to make the program “speak,” and<span>std::cin</span>to listen to the user’s “voice,” and even how to beautify output with<span>iomanip</span>.#include <iostream> #include <string> #include <iomanip> // ... std::string name; std::cout << "你的名字?"; std::cin >> name; std::cout << "你好, " << std::setw(10) << name << "!" << std::endl; -
Control Flow: You mastered
<span>if/else if/else</span>and<span>switch</span>for conditional judgments, as well as<span>for</span>,<span>while</span>, and<span>do-while</span>for loop control.if (age >= 18) { /*...*/ } else { /*...*/ } for (int i = 0; i < 10; ++i) { /*...*/ } while (/* condition */) { /*...*/ }
Now, you should be able to understand and write some simple C++ programs. This is just the beginning; the world of C++ is far broader than this!