在 C++ 中使用 getline 函数连续读取两行

Reading two line continuously using getline function in c++

我正在学习如何使用 getline 函数读取字符串。

我知道只要我们不按回车键或 getline 参数中的大小值交叉,getline 函数就会读取字符串。据我尝试使用 getline 函数读取一行字符串,我没有遇到任何问题。

但是当我试图在两个不同的字符数组中一个接一个地读取两行字符串时,我得到了我意想不到的输出。 要理解我的问题,请遵循以下行

#include <iostream>
using namespace std;
int main()
{
    char line1[10];
    char line2[10];
    cin.getline(line1,7);
    cin.getline(line2,7);
    cout << "\nline1 =" << line1 <<endl;
    cout << "line2 =" << line2 <<endl;
}

当我 运行 上面的程序要求我输入时,我给了 o运行ge 作为第一个输入并按下回车按钮。

接下来它要求我给出第二个输入。然后我给了 banana 并按下回车按钮。在这种情况下它产生了我预期的结果。但是如果输入 o运行ges 作为第一个输入它不等我输入第二个输入。

结果第 1 行存储了 o运行ge,但第 2 行保持空白。 现在我的问题是line1存储o运行ge没有错。但我不明白为什么 line2 保持空白,如果它不包含 line1 接受输入后保留的数据,我的意思是 line2 不应该包含 s 作为值。

因为 o运行ge 是一个 6 位的字,所以 getline 将存储前六位,然后在我设置 geline 7 的大小时添加一个空字符。

然后其他剩余数据将在下一次调用 getline 时分配 function.So 不应存储在 line2 中,因为在第一次读取 new_line 字符后。

为什么第2行会一直空白,为什么第一次输入后屏幕不停止输入?

std::istream::getline 数据过载。

According to cppreference,

Behaves as UnformattedInputFunction. After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):

  • end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)
  • the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.
  • count-1 characters have been extracted (in which case setstate(failbit) is executed).

强调我的。

cin.getline(line1,7);
//                ^ This is count

只能读取第 6 个字符,第 7 个字符保留为空终止符。 “oranges”是七个字符,这使 cin 处于 non-readable 错误状态,必须清除该状态才能继续阅读。第二行的阅读

cin.getline(line2,7);

立即失败,没有数据被读取。

显而易见的解决方案是

cin.getline(line1, sizeof(line1));

利用整个阵列。但是...

应测试任何 IO 事务是否成功,因此

if (cin.getline(line1, sizeof(line1)))
{
    // continue gathering 
}
else
{
    // handle error
}

是更好的选择。

更好的方法是使用 std::getline and std::string 几乎消除大小限制。