正在跳过 C++ for 循环

c++ for loop is being skipped

本文关键字:for 循环 C++      更新时间:2023-10-16

我用这个小程序做错了什么。

我刚刚开始学习 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循环中,您递增jj++),但从不触摸i。 由于您正在以i作为索引从word中读取char s,因此test最终会"wwww"

你似乎把自己弄糊涂了,所以...

让我们分解一下您要执行的操作:

如果你迭代字符串中的每个字符,然后在该索引处检查字母表的每个字母,你将有两个循环:

for(;;) {
    for(;;) {
    }
}

第一个(遍历字符串中的每个索引应在索引到达字符串末尾时结束(字符串文本以 '' 结尾):

for(int i = 0; word[i] != '' && test[i] != ''; i++) {
    for(;;) {
    }
}

第二个将检查字母表的每个字母(char temp = 'a'temp++)与给定的索引wordtestword[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));