問題:為什么我的 for 回圈沒有第三次迭代?
我注意到了什么:在下面的 for 回圈陳述句中,洗掉 if-else 陳述句允許我列印 i from 0-2 和 "1" 三次。
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 << "1" << endl 中的 "1";在第 2 次和第 3 次迭代中。
uj5u.com熱心網友回復:
z >= 0總是true因為z是一種unsigned型別。
您的程式因此回圈。盡管還有其他解決方案,但使用 along long而不是 astd::size_t作為回圈索引可能是最簡單的。
b < (user_input.length() - 1)如果user_input為空也是有問題的。利用
b 1 < user_input.length()
反而。
uj5u.com熱心網友回復:
在 for 回圈中:
for (size_t z {i - 1}; z >= 0; --z) {
the_line = user_input[z];
}
因為size_t永遠不會是負面的,所以z >= 0永遠是真實的。所以這是一個無限回圈。
您可以對其進行型別轉換:
for (long long z {static_cast<long long>(i - 1)}; z >= 0; --z) {
the_line = user_input[z];
}
或者,如果您不想對其進行型別轉換,則可以使用這種相當奇怪的方式:
for (size_t z{i}; z-- > 0; )
the_line = user_input[z];
}
uj5u.com熱心網友回復:
已經給了一個除答案:另一個C 標準的整合和高便攜性符號的型別適合z的std::ptrdiff_t。(它類似于 POSIX 的ssize_t。)
(參考標準:“std::ptrdiff_t如果可能出現負值,則用于指標算術和陣列索引。”)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380733.html
上一篇:for回圈內的awk問題
