分支语句和逻辑运算符
C++主要的分支语句有if语句,switch语句。这两种语句如下表所示。
逻辑运算无非是与,或,非,异或。假设A为1,B为0
break和continue
break语句可以跳出for循环,while循环,而且只能跳出最内层的那一个循环,如果多层循环嵌套又想要一次性全部调出怎么办呢?可以考虑goto语句,想知道的话可以百度一下,而continue语句只是结束本次循环,开启下一次循环,注意其中的区别。
文件io
文件io流和我们之前碰到的标准输入流很相似,首先定义两个对象ifstream ifile 以及ofstream ofile。接下来的事情就是把这两个对象和一个文件联系起来,然后你把infile当成cin,outfile当成cout用就行了,这里给出一个小例子以供学习
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char data[100];
// 以写模式打开文件
ofstream outfile;
outfile.open("file.txt");
如果打开文件失败,直接返回错误代码
if (!outfile.is_open())
{
exit(EXIT_FAILURE);
}
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// 向文件写入用户输入的数据
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
// 再次向文件写入用户输入的数据
outfile << data << endl;
// 关闭打开的文件
outfile.close();
// 以读模式打开文件
ifstream infile;
infile.open("file.txt");
//如果打开文件失败,直接返回错误代码
if (!infile.is_open())
{
exit(EXIT_FAILURE);
}
cout << "Reading from the file" << endl;
infile >> data;
// 在屏幕上写入数据
cout << data << endl;
// 再次从文件读取数据,并显示它
infile >> data;
cout << data << endl;
// 关闭打开的文件
infile.close();
return 0;
}