这个小程序我做错了什么。
我刚开始学习 C++,无论如何我可以接受这是一个没有实际意义的问题。我正在阅读 Prata c++ primer,它给了我一个代码示例,它采用一个 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
初始化为 ?
所以,looking at an ascii chart ,您会看到 ?
和小写字母 z
之间有很多非字母字符。
此外,在 for
循环中,您递增 j
(j++
) 但永远不要触及 i
。由于您正在以 i
作为索引从 word
中读取 char
,因此 test
最终将成为 “wwww”
。
你好像把自己弄糊涂了,所以...
让我们分解一下您要尝试做的事情:
如果您要遍历字符串中的每个字符,然后检查该索引处的每个字母,您将有两个循环:
for(;;) {
for(;;) {
}
}
第一个(遍历字符串中的每个索引应该在索引到达字符串末尾时结束(字符串文字以 '\0'
终止):
for(int i = 0; word[i] != '\0' && test[i] != '\0'; i++) {
for(;;) {
}
}
第二个将根据您在 word
中给定的索引检查字母表中的每个字母(char temp = 'a'
和 temp++
)和 test
(word[i] != test[i];
)。如果它们不相等,它会将索引 i
处的 test
的字符设置为 temp
,直到找到正确的字母。把它们放在一起,你最终会得到这个:
for(int i = 0; word[i] != '\0' && test[i] != '\0'; i++) {
for(char temp = 'a'; word[i] != test[i]; temp++) {
test[i] = temp;
}
}
当然,如果您只追求结果而不是试图自学循环和编程基础知识,那么这只是一种非常迂回的 simplay 调用方式:
memcpy(temp, word, strlen(word));
关于正在跳过 c++ for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14532658/