【发布时间】:2022-01-17 17:15:28
【问题描述】:
问题:为什么我的 for 循环没有第三次迭代?
我注意到了:在下面的 for 循环语句中,删除 if-else 语句允许我打印 0-2 和 "1" 的 i 3 次。
for (size_t i {0}; i < user_input.length(); ++i) {
cout << i << endl;
cout << user_input.length() << endl;
string the_spaces;
string the_line;
for (size_t b {i}; b < (user_input.length() - 1); ++b) {
the_spaces += " ";
}
for (size_t k {0}, y {i+1}; k < y; ++k) {
the_line += user_input[k];
}
if (i >= 1) {
cout << "Bob";
for (size_t z {i - 1}; z >= 0; --z) {
the_line += user_input[z];
}
}
else {
cout << "Beb" << endl;
}
cout << "1" << endl;
}
Output:
0 // i
3 // the user_input.length
Beb // output from if-else
1 // 1 printed at the end of the for loop expression
1 // i (2nd iteration)
3 // the user input.length
代码到此结束...既不打印 Beb 或 Bob,也不打印 cout 在第 2 次和第 3 次迭代中的 "1"。
【问题讨论】:
-
for (size_t z {i - 1}; z >= 0; --z)是无限循环。 -
这应该是学习如何调试你的程序的最佳时机。例如,使用 调试器,您可以在监视变量及其值的同时逐句执行代码。
-
甚至不应该需要调试器 - 只需打开(所有)编译器警告:任何理智的人都会警告您
z >= 0总是正确的。
标签: c++ for-loop if-statement