C++ 程序打印用户输入的数字
对象“cin”和“cout”分别用于 C++ 中的输入和输出。cin 是 istream 类的实例,并连接到标准输入设备,例如键盘。cout 是 ostream 类的实例,并连接到标准输出设备,例如显示屏。
打印用户输入数字的程序如下所示:
示例
#include <iostream>
using namespace std;
int main() {
int num;
cout<<"Enter the number:\n";
cin>>num;
cout<<"The number entered by user is "<<num;
return 0;
}输出
Enter the number: 5 The number entered by user is 5
在上面的程序中,用户使用 cin 对象输入数字。
cout<<"Enter the number:\n"; cin>>num;
然后使用 cout 对象显示该数字。
cout<<"The number entered by user is "<<num;
用户输入多个数字的一种方法是使用数组。这在下面的程序中进行了演示:
示例
#include <iostream>
using namespace std;
int main() {
int a[5],i;
cout<<"Enter the numbers in array\n";
for(i=0; i<5; i++)
cin>>a[i];
cout<<"The numbers entered by user in array are ";
for(i=0; i<5; i++)
cout<<a[i]<<" ";
return 0;
}输出
Enter the numbers in array 5 1 6 8 2 The numbers entered by user in array are 5 1 6 8 2
在上面的程序中,for 循环用于访问用户的所有数组元素。对于 for 循环的每次迭代,使用 cin 对象访问具有相应索引的数组元素。
for(i=0; i<5; i++) cin>>a[i];
之后,使用相同的 for 循环概念显示所有数组元素。
for(i=0; i<5; i++) cout<<a[i]<<" ";
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP