C++语言的基本元素:
-内置数据类型
-对象的定义
-表达式
-语句
-函数的定义和使用
C++例子:
某个书店将每本出售的图书的书名和出版社输入到一个文件中,
这些信息以书售出的时间顺序输入,每两周店主将手工计算每本书俄销售量,
以及每个出版社的销售量。
报表以出版社的名称的字母顺序排列。
算法(algorithm):
l 读销售文件
2 对文件排序——先按出版社然后在出版社内部按书名排序
3 压缩重复的书名
4 将结果写入文件
输入输出初步:
输入输出的向导符 << 将一个值向导到标准输出(cout)或标准错误(cerr)上。cout << '/n';语句等价于cout << endl;
编写一个简单的C++程序io.c
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int v1 = 2, v2 = 4;
7 cout << "Hi! The sum of v1 + v2 = ";
8 cout << v1 + v2;
9 cout << '/n';
10 return 0;
11 }
这个程序和下面的代码是等价的
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int v1 = 2, v2 = 4;
7 cout << "Hi! The sum of v1 + v2 = " << v1 + v2 << endl;
8 return 0;
9 }
运行命令:
$ g++ i.c
$ ./a.out
文件输入输出:
#include <iostream>
#include <fstream>
下面是一个简单的文件输入输出的代码
1 #include <iostream>
2 #include <fstream>
3 #include <string>
4 using namespace std;
5
6 /*将in_file中的文件类容输出到out_file中*/
7 int main()
8 {
9 //声明一个ofstream类型的对象
10 ofstream outfile( "out_file" );
11 ifstream infile( "in_file" );
12 //如果不能打开的值为false
13 if ( !outfile ) {
14 cerr << "Sorry! We were unable to open out_file!/n";
15 return -1;
16 }
17 //声明一个ifstream类型的对象
18 if ( !infile ) {
19 cerr << "Sorry! We were unable to open in_file!/n";
20 return -2;
21 }
22 string word;
23 while ( infile >> word )
24 outfile << word << ' ';
25 return 0;
26 }
只要在当前路径下创建两个文件out_file,in_file,执行下面命令就可以把in_file中的内容输出到out_file文件中
$ g++ fio.c
$ ./a.out
#include 是预处理器指示符(preprocessor directive)
using namespace std;这是using指示符(using directive)C++标准库H中的名字都是在一个称作
std的名字空间中声明的,这些名字在我们的程序文本文件中是不可件的。using指示符告诉编译器要使用在名字空间std中声明的名字。
#include <some_file.h>
#include "my_file.h"
<>表明这个文件是一个工程或标准头文件,查找过程会检查预定义的目录。我们可以通过设置搜索路径环境变量或命令行选项来修改这些目录。
()表明该文件是用户提供对的头文件,查找该文件时将从当前文件目录开始。
#ifndef
#ifdef
前者没有定义为真,后者定义了为真。#ifndef的作用:避免两个同名的预处理常量。
#ifdef的作用很显然相当一个条件语句。
C++笔记(2)
最新推荐文章于 2025-01-22 01:27:16 发布
5941

被折叠的 条评论
为什么被折叠?



