cin 对象用于从标准输入设备(即键盘)接受输入。它定义在 iostream 头文件中。
示例
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
// take integer input
cin >> num;
cout << "You entered: " << num;
return 0;
}
输出
Enter a number: 25 You entered: 25
cin 语法
cin 对象语法如下:
cin >> var_name;
这里,
带提取运算符的 cin
cin 中的"c"代表"character","in"代表"input"。因此cin表示"字符输入"。
cin 对象与提取运算符 >> 一起使用,以接收字符流。例如,
int num;
cin >> num;
在同一语句中,>> 运算符也可以使用多次来接受多个输入。
cin >> var1 >> var2 >> … >> varN;
示例 1:带提取运算符的 cin
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
cout << "Enter a number: ";
// for single input
cin >> num1;
cout << "Enter 2 numbers:" << endl;
// for multiple inputs
cin >> num2 >> num3;
cout << "Sum = " << (num1 + num2 + num3);
return 0;
}
输出
Enter a number: 9 Enter 2 numbers: 1 5 Sum = 15
带成员函数的 cin
cin 对象还可以与其他成员函数一起使用,例如 getline()、read() 等。一些常用的成员函数是:
cin.get(char &ch):读取一个输入字符并将其存储在 ch 中。cin.getline(char *buffer, int length):将字符流读取到字符串 buffer 中,它会在以下情况下停止:- 它已读取
length-1个字符,或者 - 当它找到行尾字符
'\n'或文件尾eof时。
- 它已读取
cin.read(char *buffer, int n):将流中的 n 字节(或直到文件末尾)读取到 buffer 中。cin.ignore(int n):忽略输入流中的接下来的 n 个字符。cin.eof():如果到达文件末尾 (eof),则返回一个非零值。
示例 2:带成员函数的 cin
#include <iostream>
using namespace std;
int main() {
char name[20], address[20];
cout << "Name: ";
// use cin with getline()
cin.getline(name, 20);
cout << "Address: ";
cin.getline(address, 20);
cout << endl << "You entered " << endl;
cout << "Name = " << name << endl;
cout << "Address = " << address;
return 0;
}
输出
Name: Sherlock Holmes Address: Baker Street, UK You entered Name = Sherlock Holmes Address = Baker Street, UK
cin 原型
cin 在 iostream 头文件中的原型是:
extern istream cin;
C++ 中的 cin 对象是 istream 类的一个对象。它与标准 C 输入流 stdin 相关联。
cin 对象在第一次构造 ios_base::Init 类型对象期间或之前得到确保被初始化。
在 cin 对象构造之后,cin.tie() 返回 &cout。这意味着在 cin 上的任何格式化输入操作都会强制调用 cout.flush()(如果还有待输出的字符)。
另请阅读