如何在输入中有空行时在C++中使用GETLILE()?

在C++中,如果需要从流中读取几个句子,通常首选的方法是使用GETLILE()函数。它可以一直读到遇到换行符或看到用户提供的分隔符为止。

null

下面是C++中的一个示例程序,它读取四个句子,并在结尾处用“:换行”显示它们。

// A simple C++ program to show working of getline
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str;
int t = 4;
while (t--)
{
// Read a line from standard input in str
getline(cin, str);
cout << str << " : newline" << endl;
}
return 0;
}


示例输入:

 This
 is
 Geeks
 for

正如预期的那样,产出是:

This : newline
is  : newline
Geeks : newline
for : newline

上面的输入和输出看起来不错,当输入之间有空行时可能会出现问题。

示例输入:

This

is 

Geeks

for

输出:

This : newline
 : newline
is  : newline
 : newline

它不会打印最后两行。原因是getline()会一直读取,直到遇到enter,即使没有读取任何字符。因此,即使第三行中没有任何内容,getline()也会将其视为一行。进一步观察第二行中的问题。

可以修改代码以排除此类空行。

修改代码:

// A simple C++ program that uses getline to read
// input with blank lines
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str;
int t = 4;
while (t--)
{
getline(cin, str);
// Keep reading a new line while there is
// a blank line
while (str.length()==0 )
getline(cin, str);
cout << str << " : newline" << endl;
}
return 0;
}


输入:

This

is 

Geeks

for

输出:

This : newline
is  : newline
Geeks : newline
for : newline

本文由 沙林·南达 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享