当前位置:编程学习 > C/C++ >>

C++ Primer学习笔记 - 第一章

[cpp]
#include <iostream> 
 
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; 
    system("pause"); 
    return 0; 


main 函数,返回值必须是 int 类型。

该值可以看成一个状态指示器,返回 0 往往表示成功执行,返回非0,则表示出现特定的错误。


IO 标准库, iostream 库,定义了4个IO 对象: cin 、 cout 、 cerr 、 clog。

std::endl ,具有输出换行的效果,并会刷新缓冲区,因此才能立即看到写入到流中的输出。

std::endl 的写法,包含2个冒号,这是作用域操作符,指明所属的命名空间。

 


while 语句:

[cpp] 
#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; 
    system("pause"); 
    return 0; 


for 语句:

[cpp] 
#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; 
    system("pause"); 
    return 0; 


读入未知数目的输入:

[cpp]
#include <iostream> 
 
int main() 

    int sum = 0, value;  
    std::cout << "Please Enter:" << std::endl; 
     
    while(std::cin >> value){ 
        sum += value; 
    } 
     
    std::cout << "Sum is " 
        << sum << std::endl; 
    system("pause"); 
    return 0; 

直到读入了非整数,或者,输入了文件结束符(windows 中:Ctrl + Z; Unix 中:Ctrl + D),则,while 循环终止。

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,