Learning C++ 之1.3a cout cin endl

std::cout

像之前提到的一样,cout是将程序输出到屏幕上的一个标准函数。如下面的例子:

#include <iostream>
 
int main()
{
    std::cout << "Hello world!";
    return 0;
}

为了输出多个参数 <<可以使用多次,如下:

#include <iostream>
 
int main()
{
    int x = 4;
    std::cout << "x is equal to: " << x;
    return 0;
}

这个程序的最终输出结果是:x is equal to : 4

你期望如下函数什么信息?

#include <iostream>
 
int main()
{
    std::cout << "Hi!";
    std::cout << "My name is Alex.";
    return 0;
}

你可能惊讶于输出并没有换行:Hi!My name is Alex.

std::endl

如果你想输出换行的话,那么可以考虑使用endl函数。如下:

#include <iostream>
 
int main()
{
    std::cout << "Hi!" << std::endl;
    std::cout << "My name is Alex." << std::endl;
    return 0;
}

输出结果就是:

Hi!

My name is Alex.

std::cin

std::cin和std::cout相反,std::cout是使用<<操作符向屏幕输出信息,std::cin是使用>>操作符向屏幕输入信息。如下面的例子:

//#include "stdafx.h" // Uncomment this line if using Visual Studio
#include <iostream>
 
int main()
{
    std::cout << "Enter a number: "; // ask user for a number
    int x; // no need to initialize x since we're going to overwrite that value on the very next line
    std::cin >> x; // read number from console and store it in x
    std::cout << "You entered " << x << std::endl;
    return 0;
}

你可以编译执行一下,执行时会先出现如下打印:

Enter a number:

然后你输入一个数字如:4

那么就会输出:

You entered 4

这种方式输入变量非常简单,所以以后的课程中我们会经常用到。

std::cin , std::cout , <<  ,>>

新手程序员经常弄混上面几个符号,下面是一个方便记忆的方法:

  • std::cin和std::cout 往往在语句的左边
  • std::cout 用来输出,因为有out
  • std::cin  用来输入 ,因为有in
  • std::cout 使用 <<,将数值从右值输出到控制台上
  • std::cin  使用 >>,将数值从控制台输出到变量上

个人经验总结:其实这个符号就是<< >>中国的书名号,先有输入,再有输出。中国话和英语往往是反着的所以就是输入>>,输出<<.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值