如何在C ++中使用std :: getline()?

本文详细介绍了C++中的getline()函数,包括其基本语法、如何从输入流读取数据、使用定界符分割输入,以及使用时可能遇到的问题。通过示例展示了如何正确使用该函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In this article, we’ll take a look at using the function std::getline() in C++. This is a very handy function if you want to read characters from an input stream.

在本文中,我们将介绍在C ++中使用函数std :: getline()的情况。 如果您想从输入流中读取字符,这是一个非常方便的功能。

Let’s find out how we can use this properly, using some illustrative examples.

让我们使用一些说明性示例来找出如何正确使用它。



C ++中std :: getline()的基本语法 (Basic Syntax of std::getline() in C++)

This function reads characters from an input stream and puts them onto a string.

此函数从输入流中读取字符,并将其放入字符串中

We need to import the header file <string>, since getline() is a part of this file.

我们需要导入头文件<string> ,因为getline()是此文件的一部分。

While this takes template arguments, we’ll focus on string inputs (characters) , since the output is written to a string.

尽管这需要模板参数,但我们将重点放在字符串输入(字符)上,因为输出已写入字符串。


istream& getline(istream&amp; input_stream, string& output, char delim);

What this says is that getline() takes an input stream, and writes it to output. Delimiters can be optionally specified using delim.

这说明getline()接受输入流,并将其写入output 。 可以使用delim指定分隔符。

This also returns a reference to the same input stream, but for most cases, we don’t need this handle.

这也返回对相同输入流的引用,但是在大多数情况下,我们不需要此句柄。

使用std :: getline()从输入流中读取 (Using std::getline() to read from input streams)

Now that we know the basic syntax, let’s get input from std::cin (standard input stream) to a string.

现在我们已经了解了基本语法,现在让我们从std::cin (标准输入流)向字符串获取输入。


#include <iostream>
#include <string>

int main() {
    // Define a name (String)
    std::string name;

    std::cout << "Enter the name: ";

    // Get the input from std::cin and store into name
    std::getline(std::cin, name);

    std::cout << "Hello " << name << "!\n";

    return 0;
}

Output

输出量


Enter the name: JournalDev
Hello JournalDev!

Indeed, we were able to get the input from std::cin without any problems!

确实,我们能够毫无问题地从std::cin获得输入!

Let’s now take another example, where we have a file input.txt containing the following content:

现在再来看一个示例,其中有一个包含以下内容的文件input.txt


$ cat input.txt
Hello from JournalDev
Second Line of file
Last line

Let’s now read the file line by line and store them into a vector of strings!

现在让我们逐行读取文件并将其存储到字符串向量中!

The core logic will be to keep reading using std::getline(file) until the input stream reaches EOF.

核心逻辑是继续使用std::getline(file)读取,直到输入流到达EOF为止。

We can easily write this using this format:

我们可以使用以下格式轻松编写此代码:


std::ifstream infile("input.txt");

// Temporary buffer
std::string temp;

// Get the input from the input file until EOF
while (std::getline(infile, temp)) {
  // Add to the list of output strings
  outputs.push_back(temp);
}

The complete code is shown below:

完整的代码如下所示:


#include <iostream>
#include <string>
#include <vector> // For std::vector
#include <fstream> // For std::ifstream and std::ofstream

int main() {
    // Store the contents into a vector of strings
    std::vector<std::string> outputs;

    std::cout << "Reading from input.txt....\n";

    // Create the file object (input)
    std::ifstream infile("input.txt");

    // Temporary buffer
    std::string temp;

    // Get the input from the input file until EOF
    while (std::getline(infile, temp)) {
        // Add to the list of output strings
        outputs.push_back(temp);
    }

    // Use a range-based for loop to iterate through the output vector
    for (const auto& i : outputs)
        std::cout << i << std::endl;

    return 0;
}

Output

输出量


Reading from input.txt....
Hello from JournalDev
Second Line of file
Last line

在C ++中使用std :: getline()使用定界符分割输入 (Using std::getline() in C++ to split the input using delimiters)

We can also use the delim argument to make the getline function split the input in terms of a delimiter character.

我们还可以使用delim参数使getline函数根据分隔符对输入进行分割。

By default, the delimiter is \n (newline). We can change this to make getline() split the input based on other characters too!

默认情况下,分隔符为\n (换行符)。 我们可以更改它,使getline()根据其他字符拆分输入!

Let’s set the delim character to a space ‘ ‘ character to the above example and see what happens!

让我们在上面的示例中将delim字符设置为空格''字符,看看会发生什么!


#include <iostream>
#include <string>
#include <vector> // For std::vector
#include <fstream> // For std::ifstream and std::ofstream

int main() {
    // Store the contents into a vector of strings
    std::vector<std::string> outputs;

    std::cout << "Reading from input.txt....\n";

    // Create the file object (input)
    std::ifstream infile("input.txt");

    // Temporary buffer
    std::string temp;

    // Get the input from the input file until EOF
    while (std::getline(infile, temp, ' ')) {
        // Add to the list of output strings
        outputs.push_back(temp);
    }

    // Use a range-based for loop to iterate through the output vector
    for (const auto& i : outputs)
        std::cout << i << std::endl;

    return 0;
}

Output

输出量


Reading from input.txt....
Hello
from
JournalDev
Second
Line
of
file
Last
line

Indeed, we have our space separated string now!

确实,我们现在有了用空格分隔的字符串!



使用std :: getline()的潜在问题 (Potential Issues with using std::getline())

While std::getline() is a very useful function, there could be some problems that you may face when using it along with some input streams such as std::cin.

尽管std::getline()是一个非常有用的函数,但在将其与诸如std::cin类的一些输入流一起使用时,可能会遇到一些问题。

  • std::getline() does not ignore any leading white-space / newline characters.

    std::getline() 忽略任何前导空格/换行符。

Because of this, if you call std::cin >> var; just before getline(), there will be a newline still remaining in the input stream, after reading the input variable.

因此,如果您调用std::cin >> var; 在读取输入变量之后,就在getline()之前,在输入流中仍然会有换行符。

So, if you call getline() immediately after cin, you will get a newline instead, since it is the first character in the input stream!

因此,如果您在cin之后立即调用getline() ,则会得到一个换行符,因为它是输入流中的第一个字符!

To avoid this, simply add a dummy std::getline() to consume this new-line character!

为避免这种情况,只需添加一个虚拟std::getline()即可使用此换行符!

The below program shows an issue with using cin just before getline().

以下程序显示了在getline()之前使用cin的问题。


#include <iostream>
#include <string>

int main() {
    // Define a name (String)
    std::string name;

    int id;

    std::cout << "Enter the id: ";

    std::cin >> id;

    std::cout << "Enter the Name: ";

    // Notice std::cin was the last input call!
    std::getline(std::cin, name);

    std::cout << "Id: " << id << std::endl;
    std::cout << "Name: " << name << "\n";

    return 0;
}

Output

输出量


Enter the id: 10
Enter the Name: Id: 10
Name: 

Notice that I wasn’t able to enter the name at all! Since a trailing newline was there in the input stream, it simply took that, and since it is a delimiter, it stopped reading!

请注意,我根本无法输入名称! 由于输入流中存在尾随换行符,因此它就简单地接受了它,并且由于它是一个定界符,因此它停止了读取!

Now let’s add a dummy std::getline() call just before our actual std::getline().

现在让我们在实际的std::getline()之前添加一个虚拟的std::getline()调用。


#include <iostream>
#include <string>

int main() {
    // Define a name (String)
    std::string name;

    int id;

    std::cout << "Enter the id: ";

    std::cin >> id;

    std::cout << "Enter the Name: ";

    // Add a dummy getline() call
    std::getline(std::cin, name);
    // Notice std::cin was the last input call!
    std::getline(std::cin, name);

    std::cout << "Id: " << id << std::endl;
    std::cout << "Name: " << name << "\n";

    return 0;
}

Output

输出量


Enter the id: 10
Enter the Name: JournalDev
Id: 10
Name: JournalDev

We’ve finally fixed our bug! This hopefully makes you think a bit more before blindly using std::getline().

我们终于修复了我们的错误! 希望这会使您在盲目使用std::getline()之前多加考虑。

Unfortunately, there are no elegant methods to get input in C++, so we must make do with what we have!

不幸的是,没有优雅的方法来获取C ++中的输入,因此我们必须利用已有的东西!



结论 (Conclusion)

In this article, we learned about using std::getline() in C++. We also look at some examples which illustrate the power, and pitfalls of this function.

在本文中,我们学习了在C ++中使用std :: getline()的知识。 我们还将查看一些示例,这些示例说明了此功能的功能和缺陷。

参考资料 (References)



翻译自: https://www.journaldev.com/39743/getline-in-c-plus-plus

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值