《C++PrimerPlus》第6章 分支语句和逻辑运算符

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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值