c++ primer学习笔记(1)
2009-04-03 10:21 Clingingboy 阅读(801) 评论(0) 编辑 收藏 举报
学习笔记只为帮助自己记忆,写的并不严谨,以自己理解为主.若看到此文的人,发现错误请指出,非常感谢.
1.简单的c++程序
还是以main函数为入口点,可以有返回值,也可以返回值为void,文件后缀名为cpp(以不同编译为准)
int main() { return 0; }
2.标准库
即c++的扩展函数库
3.iostream库
标准库中用于基本标准输出和输入的库
先看以下两个方法
(1)cin 标准输入 (2)cout 标准输出(c读作see, see-in,see-out)
4.使用iostream库
#include <iostream> /* Simple main function: Read two numbers and write their sum */ int main() { std::cout << "Enter two numbers:" << std::endl; int v1, v2; std::cin >> v1 >> v2; std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl; return 0; }
分析上面程序
(1)头文件(header):iostream被称之为
(2)#include:程序要使用标准库,则必须先使用引用该文件,库前后加尖括号
(3)命名空间(namespace):方法被定义在命名空间中,为了防止命名冲突,如命名空间std,副作用则是调用函数的时候要引用命名空间.
(4)作用域操作符(scope operator ::),如std::cout 即使用iostream的cout则需要 namespace +”::"+cout
(5)输出操作符和输入操作符(<<,>>) 如上程序
std::cout << "Enter two numbers:" << std::endl;
先输出"Enter two numbers:" ,iostream的endl表示换行
int v1, v2; std::cin >> v1 >> v2; //用户输入两个数字
接着再输出结果,以下为程序输出结果.
5.c++的部分控制结构
(1)while语句
#include <iostream> int main() { int sum = 0, val = 1; // keep executing the while until val is greater than 10 while (val <= 10) { sum += val; // assigns sum + val to sum ++val; // add 1 to val } std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl; return 0; }
输出结果:
(2)for语句
输出结果同上
#include <iostream> int main() { int sum = 0; // sum values from 1 up to 10 inclusive for (int val = 1; val <= 10; ++val) sum += val; // equivalent to sum = sum + val std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl; return 0; }
(3)if语句
#include <iostream> int main() { std::cout << "Enter two numbers:" << std::endl; int v1, v2; std::cin >> v1 >> v2; // read input // use smaller number as lower bound for summation // and larger number as upper bound int lower, upper; if (v1 <= v2) { lower = v1; upper = v2; } else { lower = v2; upper = v1; } int sum = 0; // sum values from lower up to and including upper for (int val = lower; val <= upper; ++val) sum += val; // sum = sum + val std::cout << "Sum of " << lower << " to " << upper << " inclusive is " << sum << std::endl; return 0; }
以上为第一章快速入门,省略类这一部分.