gpt4 book ai didi

c++ - 而vs对于陈述的不同行为

转载 作者:行者123 更新时间:2023-12-01 15:12:27 26 4
gpt4 key购买 nike

我试图理解为什么while循环能按预期工作,但是(在我看来)for循环的等效项却不起作用。

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream ifs{ "loop-in.txt" };
if (!ifs)
perror("can't open input file ");
vector<int> ys;

while (true)
{
int y; // get a clean int each time around
if (!(ifs >> y)) // if it cannot read a int
break;
ys.push_back(y); // else: push it into the vector = meaning if(cin>>y)
}
cout << "the vector is:\n";
for (int x : ys)
cout << x << '\n';
}
loop-in.txt包含随机整数:2 3 4 5 6 1 12 34 3,并且输出是预期的:
the vector is:
2
3
4
5
6
1
12
34
3
但是,当我进行此for循环时,输出结果很奇怪。见下文。
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream ifs{ "loop-in.txt" };
if (!ifs)
error("can't open input file ");
vector<int> ys;
for (int y; ifs >> y;)
{
if (!(ifs >> y))
break;
ys.push_back(y);
}
cout << "the vector is:\n";
for (int x : ys)
cout << x << '\n';
}
for循环的输出:
the vector is:
3
5
1
34
当我偶然发现此问题时,我试图了解在while循环内声明变量与for循环有何不同。
如果删除if语句,则for循环输出正确。
但是我不明白为什么当while循环工作正常时,为什么不能使用if语句。
感谢大家抽出宝贵的时间。

最佳答案

for (int y; ifs >> y;)  // <-- Read here.
{
if (!(ifs >> y)) // <-- And read here, overwriting read above.
break;
ys.push_back(y); // <-- Only pushes every second one.
}
在该循环的每次迭代中都有两次读取,第一次在 for语句中,第二次在循环体中。这意味着您将只存储所读取值的一半。
等效的 while循环如下所示(可能不完全相同,但效果差不多):
while (true)
{
int y; // get a clean int each time around
if (!(ifs >> y)) // if it cannot read a int
break;
if (!(ifs >> y)) // if it cannot read a int
break;
ys.push_back(y);
}
要么停止阅读 for语句,要么停止阅读正文。

关于c++ - 而vs对于陈述的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63261258/

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