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 使用 >>,将数值从控制台输出到变量上