C++ 入门
-
C++ 文件的后缀
.cc, .cxx, .cpp, .cp, .c
-
通过命令行编译程序
1. 编写文件 prog1.cc
int main()
{
return 0;
}
2. 执行命令:
CC prog1.cc
或者:
g++ -o prog1 prog1.cc
3. 运行生成的文件
Linux 系统生成 a.out
Windows 系统生成 prog1.exe
./a.out
4. 获取执行结果
echo $?
- 输入/输出流
iostream
istream
: 输入流;cin
: 标准输入流;
ostream
: 输出流;cout
: 标准输出流;cerr
: 打印错误信息,用于处理 warning, error;clog
: 打印一般信息;
// 用户输入两个值,计算这两个值的和
#include <iostream>
/*
* sum function:
* Read two numbers and write their sum
*/
int main()
{
// prompt user to enter two numbers
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
return 0;
}
4.条件控制
// 需求: 将1至10之间的数累加
// === while 循环
#include <iostream>
int main()
{
int sum = 0, val = 1;
while (val <= 10) {
sum += val;
++val;
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;
}
// === for 循环
#include <iostream>
int main()
{
int sum = 0;
for (int val = 1; val <= 10; ++val)
sum += val;
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;
}
参考资料: