C++ istream

C++的 istream 类提供了一套用于从各种输入源读取数据的函数和运算符。

在使用 istream 类之前,我们需要在程序中包含 <iostream> 头文件。

#include <iostream>

示例 1:从控制台读取数据

要使用 istream 从控制台读取数据,可以使用 cin 对象和提取运算符 >>。下面是一个示例:

#include <iostream>
using namespace std;

int main() {

    int entered_number;

    cout << "Enter an integer: ";

// read data from the console cin >> entered_number;
cout << "You entered: " << entered_number << endl; return 0; }

输出

Enter an integer: 3
You entered: 3

在此示例中,cin 代表从键盘读取数据的标准输入流。我们使用 >> 运算符将用户输入提取并存储在 number 变量中。


get() 函数

istream 类的 get() 函数主要用于从输入流中读取单个字符。

主要特点

  • 读取字符:它从输入流中读取下一个字符,并推进流的内部位置指示器。
  • 单个字符:与 >> 运算符不同,get() 按原样读取字符,包括空格、制表符和换行符。
  • 字符提取:您可以使用它将字符提取到 char 类型的变量中,或将它们存储在字符数组(C 字符串)中。
  • 分隔符控制:它允许您将分隔符字符指定为可选参数。当您指定分隔符时,get() 会在遇到该分隔符时停止读取字符。这对于读取单词或行很有用。

示例 2:C++ get() 函数

#include <iostream>
using namespace std; 

int main() {

    char ch;
    
    cout << "Enter a sentence: ";

    // read the character one by one
    // until a new line is encountered
while (cin.get(ch) && ch != '\n') { cout << ch; }
return 0; }

输出

Enter a sentence: Hello World
Hello World

在这里,我们使用 cin.get() 从用户那里读取单个字符。

请注意这段代码:

while (cin.get(ch) && ch != '\n') {
    cout << ch;
}

该循环逐个字符地从标准输入读取,直到遇到换行符为止。在每次迭代中,它会打印读取到的字符。


C++ getline() 函数

istream 中的 getline() 函数用于从指定输入流(如用于标准输入的 cin)中读取一行文本。

主要特点

  • 读取行:与 get() 函数不同,getline() 读取整行文本,直到指定的分隔符或行尾。
  • 分隔符控制:您可以指定一个分隔符字符,例如指示行尾的字符。这允许您按顺序读取多行文本。
  • 缓冲区大小:它接受一个可选参数来指定要读取的最大字符数,从而防止缓冲区溢出并优雅地处理长行。

示例 3:C++ getline() 函数

#include <iostream>
using namespace std; 

int main() {

    string line;
    
    cout << "Enter a line of text: ";

// read a line of input from user getline(cin, line);
cout << "You entered: " << line << endl; return 0; }

输出

Enter a line of text: Hello
You entered: Hello

C++ ignore() 函数

ignore() 函数用于跳过输入流中的指定长度的字符。

#include <iostream>
using namespace std;

int main() {

    cout << "Enter a line of text: ";

    char ch;

// ignore the next 5 characters from standard input cin.ignore(5);
// read the sixth character and print the value if (cin.get(ch)) { cout << "Next character after ignoring 5 characters: " << ch << endl; } return 0; }

输出

Enter a line of text: 12345678
Next character after ignoring 5 characters: 6

在这里,cin.ignore(5); 指示输入流忽略用户输入的下一个五个字符。

之后,if 条件 cin.get(ch) 尝试从输入流中读取前五个字符被忽略后的下一个字符。如果成功,则将其存储在 ch 变量中。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战