gpt4 book ai didi

c++ - 如何使用带有特殊整数的输入重定向作为分隔符直到eof

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:41 25 4
gpt4 key购买 nike

我需要使用输入重定向将整数存储到两个单独的链表中。整数集由一个特殊的整数 99999 分隔。我需要帮助才能读取到文件末尾并忽略 99999。另外因为输入末尾没有 99999 我无法使用它来停止它。

输入样本9 1 7 8 3999996 5 4 3 11 -2

如果我使用的是 fstream,我觉得我可以只使用 eof 函数。然而,当尝试通过重定向来做到这一点时,它似乎永远不会结束。

LinkedList L1, L2; //Two linked lists
int x;


while(1)
{
cin>>x;
L1.insertNode(x);//Function to add to linked list
if(x==99999) break; //Attempt at ignoring 99999
}
while(1)
{
cin>>x;
L2.insertNode(x);
if(x=='\n') break; // Attempt to stop at eof
}

最佳答案

您可以利用 ifstream::operator bool () 在 EOF 处返回 false 的事实来终止循环。

代码(修改为使用std::list):

std::list <int> L1, L2;
int x;

while(std::cin >> x)
{
L1.push_back(x);//Function to add to linked list
if (x==99999) break; //Attempt at ignoring 99999
}

while(std::cin >> x)
L2.push_back(x);

Live demo

关于c++ - 如何使用带有特殊整数的输入重定向作为分隔符直到eof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892307/

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