当前位置:嗨网首页>书籍在线阅读

14-其他C++语句

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

2.3 其他C++语句

再来看几个C++语句的例子。程序清单2.3中的程序对前一个程序进行了扩展,要求在程序运行时输入一个值。为实现这项任务,它使用了cin,这是与cout对应的用于输入的对象。另外,该程序还演示了cout对象的多功能性。

程序清单2.3 getinfo.cpp

// getinfo.cpp -- input and output
#include <iostream>
int main()
{
    using namespace std;
    int carrots;
    cout << "How many carrots do you have?" << endl;
    cin >> carrots; // C++ input
    cout << "Here are two more. ";
    carrots = carrots + 2;
// the next line concatenates output
    cout << "Now you have " << carrots << " carrots." << endl;
    return 0;
}

程序调整

如果您发现在以前的程序清单中需要添加cin.get(),则在这个程序清单中,需要添加两条cin.get()语句,这样才能在屏幕上看到输出。第一条cin.get()语句在您输入数字并按Enter键时读取输入,而第二条cin.get()语句让程序暂停,直到您按Enter键。

下面是该程序的运行情况:

How many carrots do you have?
12
Here are two more. Now you have 14 carrots.

该程序包含两项新特性:用cin来读取键盘输入以及将四条输出语句组合成一条。下面分别介绍它们。