我的嵌套循环只打印一个char,'c',这是要打印的正确的第一个char,但我无法弄清楚为什么我的循环不会在字母表中循环。确定我的循环错误的任何帮助都会很棒。
#include <stdio.h>
#include <stdlib.h>
void problem_1_function();
int main(){
problem_1_function();
return (0);
}
void problem_1_function(){
FILE *the_cipher_file;
the_cipher_file = fopen("cipher.txt", "r");
FILE *the_message_file;
the_message_file = fopen("message.txt", "r");
FILE * the_decode_file;
the_decode_file = fopen("decode.txt", "w");
int the_letter_counter = 0;
int the_alphabet_array[100];
int size_of_alphabet = 0;
int size_of_message = 0;
int the_message_counter = 0;
int the_message_array[100];
char the_decode_array [15];
char the_letter_char[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z'};
if(the_decode_file == NULL){
printf("Error opening file!\n");
}
if(!the_cipher_file){
printf("Error: Filename \"cipher.txt\" not found!\n");
}
while(fscanf(the_cipher_file, " %d%*[,] ", &size_of_alphabet) > 0 && the_letter_counter < 100){
the_alphabet_array[the_letter_counter] = size_of_alphabet;
//printf("%d ", size_of_alphabet);
the_letter_counter++;
}
if(!the_message_file){
printf("Error: Filename \"cipher.txt\" not found!\n");
}
while(fscanf(the_message_file, " %d%*[,] ", &size_of_message) > 0 && the_message_counter < 100){
the_message_array[the_message_counter] = size_of_message;
//printf("%d ", size_of_message);
the_message_counter++;
}
int message_equals_cipher = 0;
int message_equals_cipher2 = 0;
for(message_equals_cipher; message_equals_cipher < sizeof(the_message_array); message_equals_cipher++){ //these nested loops go through the alphabet to print letters corresponding to arrays...
for(message_equals_cipher2; message_equals_cipher2 < 26; message_equals_cipher2++){
if(the_message_array[message_equals_cipher] == the_alphabet_array[message_equals_cipher2]){
the_decode_array[message_equals_cipher] = the_letter_char[message_equals_cipher2];
fprintf(the_decode_file, "%c", the_decode_array[message_equals_cipher]);
}
}
}
fclose(the_cipher_file);
fclose(the_message_file);
fclose(the_decode_file);
}
答案 0 :(得分:4)
int message_equals_cipher = 0;
int message_equals_cipher2 = 0;
for(message_equals_cipher; ...
for(message_equals_cipher2; ...
你在循环之外将它们设置为0 ..你的for
语句的初始化表达式什么都不做 - 如果你将警告级别设置得足够高,你的编译器应该告诉你。因为你没有重置message_equals_cipher2
,你的内部循环只会运行一次。你想要
for(message_equals_cipher = 0; ...
for(message_equals_cipher2 = 0; ...
如果您正在编译C99或更高版本,则可以执行
for(int message_equals_cipher = 0; ...
for(int message_equals_cipher2 = 0; ...
并摆脱先前对这些变量的定义。
答案 1 :(得分:0)
是的,嵌套for
循环中的问题是您未在第二个message_equals_cipher2
循环中将0
变量初始化为for
。
嵌套代码应该是:
for(message_equals_cipher; message_equals_cipher < sizeof(the_message_array); message_equals_cipher++)
{
for(message_equals_cipher2=0; message_equals_cipher2 < 26; message_equals_cipher2++)
{
// Your stuff
}
}
我同意jim,而不是在嵌套message_equals_cipher
循环之前初始化变量message_equals_cipher2
和for
。您可以按指定的jim进行操作。