博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在C ++中使用std :: getline()?
阅读量:2530 次
发布时间:2019-05-11

本文共 7973 字,大约阅读时间需要 26 分钟。

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& 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 
#include
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: JournalDevHello 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.txtHello from JournalDevSecond Line of fileLast line

Let’s now read the file line by line and store them into a 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 bufferstd::string temp;// Get the input from the input file until EOFwhile (std::getline(infile, temp)) {  // Add to the list of output strings  outputs.push_back(temp);}

The complete code is shown below:

完整的代码如下所示:

#include 
#include
#include
// For std::vector#include
// For std::ifstream and std::ofstreamint main() { // Store the contents into a vector of strings std::vector
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 JournalDevSecond Line of fileLast 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 
#include
#include
// For std::vector#include
// For std::ifstream and std::ofstreamint main() { // Store the contents into a vector of strings std::vector
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....HellofromJournalDevSecondLineoffileLastline

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 
#include
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: 10Enter the Name: Id: 10Name:

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 
#include
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: 10Enter the Name: JournalDevId: 10Name: 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)

  • std::getline()

    std :: getline()
  • on using std::getline()

    关于使用std :: getline()的


翻译自:

转载地址:http://wqozd.baihongyu.com/

你可能感兴趣的文章
gethostbyname与sockaddr_in的完美组合
查看>>
kibana的query string syntax 笔记
查看>>
旋转变换(一)旋转矩阵
查看>>
thinkphp3.2.3 bug集锦
查看>>
[BZOJ 4010] 菜肴制作
查看>>
C# 创建 读取 更新 XML文件
查看>>
KD树
查看>>
VsVim - Shortcut Key (快捷键)
查看>>
C++练习 | 模板与泛式编程练习(1)
查看>>
HDU5447 Good Numbers
查看>>
08.CXF发布WebService(Java项目)
查看>>
java-集合框架
查看>>
RTMP
查看>>
求一个数的整数次方
查看>>
点云PCL中小细节
查看>>
铁路信号基础
查看>>
RobotFramework自动化2-自定义关键字
查看>>
[置顶] 【cocos2d-x入门实战】微信飞机大战之三:飞机要起飞了
查看>>
BABOK - 需求分析(Requirements Analysis)概述
查看>>
第43条:掌握GCD及操作队列的使用时机
查看>>