正在跳过 C++ for 循环
c++ for loop is being skipped
我用这个小程序做错了什么。
我刚刚开始学习 c++,无论如何,我可以接受这是一个有争议的问题。我正在通读 Prata c++ 入门,它给了我一个代码示例,它采用一个 char 数组并在 for 循环中使用 strcmp(),该循环按顺序迭代以"?"开头的 ASCII 代码,直到测试字符变量 ==s 来自另一个字符的设置值。
认为我可以超越这本书,我试图创建一个类似的程序,它接受一个 char 数组,并使用 for 循环将采用一个测试 char 数组并遍历数组的每个值,直到两个变量相等。
我将程序简化为仅采用 for 循环中每个数组的第一个数组,因为我遇到了一个问题,程序似乎只是跳过 for 循环并终止。
下面是首先是 prata 代码片段,然后是我的一段代码。任何反馈(甚至是辱骂性的>_<)都会很有用。
#include <iostream>
#include <cstring>
int main() {
using namespace std;
char word[5] = "?ate";
for (char ch = ‘a’; strcmp(word, "mate"); ch++) {
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends, word is " << word << endl;
return 0;
}
我的代码(虽然可能做得不好,但我可以接受)
#include <iostream>
#include <cstring>
int main() {
using namespace std;
char word[5] = "word";
char test[5] = "????";
int j = 0;
int i = 0;
cout << "word is " << word << "nTest is " << test << endl;
cout << word[0] << " " << test[0] << endl;
for (char temp = '?'; word[0] == test[0] || temp == 'z'; temp++) {
if ((word[i]) == (test[j])) {
test[j] = temp;
j++;
temp = '?';
}
test[j] = temp++;
cout << test << endl; //Added to see if the for loop runs through once,
//which is does not
}
return 0;
}
您的for
循环永远不会启动,因为您的状况如下所示:
word[0] == test[0] || temp == 'z'
将始终在第一次传递时返回 false。 由于temp
初始化为'?'
并且word[0]
(w
)不等于test[0]
(?
),你的循环永远不会开始。
此外,您已将temp
初始化为 ?
,因此,查看 ASCII 图表,您会发现 ?
和小写z
之间有很多非字母字符。
此外,在for
循环中,您递增j
(j++
),但从不触摸i
。 由于您正在以i
作为索引从word
中读取char
s,因此test
最终会"wwww"
。
你似乎把自己弄糊涂了,所以...
让我们分解一下您要执行的操作:
如果你迭代字符串中的每个字符,然后在该索引处检查字母表的每个字母,你将有两个循环:
for(;;) {
for(;;) {
}
}
第一个(遍历字符串中的每个索引应在索引到达字符串末尾时结束(字符串文本以 ' '
结尾):
for(int i = 0; word[i] != ' ' && test[i] != ' '; i++) {
for(;;) {
}
}
第二个将检查字母表的每个字母(char temp = 'a'
和temp++
)与给定的索引word
和test
(word[i] != test[i];
)。 如果它们不等效,它会将索引 i
处的 test
字符设置为 temp
,直到找到正确的字母。 把这一切放在一起,你最终会得到这个:
for(int i = 0; word[i] != ' ' && test[i] != ' '; i++) {
for(char temp = 'a'; word[i] != test[i]; temp++) {
test[i] = temp;
}
}
当然,如果你只是为了结果,而不是试图自学循环和编程基础知识,那么这只是一种非常迂回的模拟游戏调用方式:
memcpy(temp, word, strlen(word));
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式