6.1 if语句
6.2 逻辑表达式
6.3 字符函数库cctype
6.4 ?:运算符
使用条件表达式比较两个数的大小
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cout << "Enter two integers:";
cin >> a >> b;//连续捕获两个整型变量
c = a > b ? a : b;//如果a大于b,则把a赋值给c
cout << "The larger of " << a << " and " << b << " is " << c << endl;
return 0;
}
6.5 switch语句
用switch实现计算器
#include <iostream>
using namespace std;
int main() {
char op;
double num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op) {
case '+':
cout << num1 << " + " << num2 << " = " << num1+num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1-num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1*num2;
break;
case '/':
if(num2 == 0)
cout << "Error: division by zero";
else
cout << num1 << " / " << num2 << " = " << num1/num2;
break;
default:
cout << "Error: invalid operator";
break;
}
return 0;
}
6.6 break和continue语句
6.7 读取数字的循环
输入错误后继续读取
#include <iostream>
#include <string>
using namespace std;
int main() {
const int size = 5;
int nums[size];
for (int i = 0; i < size; i++) {
cout << "Round #" << i + 1 << ": " << endl;
// 当输入不合法的时候
while (!(cin >> nums[i])) {
cin.clear(); // 重置cin
while (cin.get() != '\n'); // 消耗到所有错误输入
cout << "Please enter a number:";
}
}
return 0;
}
6.8 简单文件输入/输出
写入文本文件
#include <iostream>
#include <fstream> // 头文件
using namespace std;
int main(){
int num;
cout << "Please enter a number:" << endl;
cin >> num;
ofstream outFile; // 创建对象
outFile.open("num.txt"); // 使用对象的方法,如果文件已存在,输入会覆盖文件内容
outFile << "You entered the number:" << num << endl;
outFile.close();
}
读取文本文件
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(){
char filename[20] = "num.txt";
ifstream inFile;
inFile.open(filename);
if (!inFile.is_open()) {
cout << "Program terminating." << endl;
exit(EXIT_FAILURE);
}
cout << "Successfully open the file." << endl;
int num;
// 判断读取是否成功
while (inFile.good()) {
inFile >> num;
cout << "The number is: " << num << endl;
}
if (inFile.eof()) // 如果读到了文件末尾
cout << "End of file reached." << endl;
else if (inFile.fail()) // 读到一半文件不匹配
cout << "Input terminated by data mismatched." << endl;
else
cout << "Input terminated by unkown reason." << endl;
inFile.close();
}