C++ 用户输入
C++ 用户输入
您已经了解到 cout 用于输出(打印)值。现在我们将使用 cin 获取用户输入。
cin 是一个预定义变量,它使用提取运算符(>>)从键盘读取数据。
在下面的实例中,用户可以输入一个存储在变量 x 中的数字。然后我们打印 x 的值:
实例
#include <stdio.h>int main() {// Create an integer variable that will store the number we get from the userint myNum;// Ask the user to type a numberprintf("Type a number and press enter: \n");// Get and save the number the user typesscanf("%d", &myNum);// Print the number the user typedprintf("Your number is: %d", myNum);return 0;}
cout 的发音是 "see-out"(向外看)。用于输出,并使用插入运算符(<<)
>>)创建一个简单的计算器
在本例中,用户必须输入两个数字。然后我们通过计算(相加)两个数字来打印总和:
实例
#include <iostream>using namespace std;int main() {int x, y;int sum;cout << "Type a number: ";cin >> x;cout << "Type another number: ";cin >> y;sum = x + y;cout << "Sum is: " << sum;return 0;}
好了!你刚刚建立了一个基本的计算器!