判断 `cin.getline()` 是否成功
Figuring out whether `cin.getline()` succeeds
这是基本代码片段:
while (true)
{
cin.getline(str, STRSIZE);
if (str[0] == '\n') { break; }
}
本质上,当用户输入一个孤独的return键时,循环应该结束。
当然,这段代码是行不通的,因为 \n
被刷新了,永远不会在 str
中结束,以验证是否输入了一个孤独的 \n
。我不好奇为什么这不起作用;我知道为什么。
How can you verify that a lonely \n
was entered, hence exiting the while-loop
?
我知道可以做到以下几点:
while (cin >> str);
但是:
>>
一次只取一个字
- 在我的实际代码中,使用了
for-loop
,而不是 while-loop
。
如果cin.getline()
读取一行失败,cin
会处于错误状态。
您可以使用:
while (cin.getline(str, STRSIZE))
{
if ( str[0] == '[=10=]' ) { break; }
// Use str
}
这是基本代码片段:
while (true)
{
cin.getline(str, STRSIZE);
if (str[0] == '\n') { break; }
}
本质上,当用户输入一个孤独的return键时,循环应该结束。
当然,这段代码是行不通的,因为 \n
被刷新了,永远不会在 str
中结束,以验证是否输入了一个孤独的 \n
。我不好奇为什么这不起作用;我知道为什么。
How can you verify that a lonely
\n
was entered, hence exiting thewhile-loop
?
我知道可以做到以下几点:
while (cin >> str);
但是:
>>
一次只取一个字- 在我的实际代码中,使用了
for-loop
,而不是while-loop
。
如果cin.getline()
读取一行失败,cin
会处于错误状态。
您可以使用:
while (cin.getline(str, STRSIZE))
{
if ( str[0] == '[=10=]' ) { break; }
// Use str
}