C ++程序打印用户输入的号码
在C++中,对象“cin”和“cout”分别用于输入和输出。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]<<" ";