gpt4 book ai didi

c++ - 使用 getline(cin,n) 输入;没有打印第一个输入,我也没有使用 cin>> 在任何地方输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:50:27 24 4
gpt4 key购买 nike

我正在尝试打印输入,直到用户给出空白输入。所以,我使用了 getline(cin,input)。但是,当我使用 getline(cin,input) 时。它在提供输出时跳过第一个输入。

#include <iostream>
using namespace std;
int main() {
while(1)
{
string n;
getline(cin, n);
while(getline(cin,n) && !n.empty())
{
cout<<n<<endl;;
}
if(n.empty())
break;
}
return 0;
}

示例输入:

12  
2

获得的输出:

2

需要的输出:

12   
2

最佳答案

你的代码询问行两次:

1) 嵌套循环之前

  getline(cin, n);

2) 嵌套循环条件内

  while(getline(cin,n) && !n.empty())

我的建议是简化程序如下:

#include <iostream>
#include <string>
using namespace std;
int main() {
while(1) // only one loop is needed
{
string n;
getline(cin, n); // read line
if(n.empty()) // check line
break; // stop loop
else
{
cout << n << endl; // print line
}
}
return 0;
}

或者只保留没有while(1)的嵌套循环,例如:

#include <iostream>
#include <string>
using namespace std;
int main() {
string n;

while(getline(cin,n) && !n.empty())
{
cout<<n<<endl;
}

return 0;
}

关于c++ - 使用 getline(cin,n) 输入;没有打印第一个输入,我也没有使用 cin>> 在任何地方输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29935475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com