我从文件中读取一个临时变量,这是一个单词,例如然而,当我提取第一个字符时,“和”,例如temp [1],程序在运行时崩溃,我尝试了断点,它就在这一行。
这是我运行代码时发生的事情:http://prntscr.com/2vzkmp
当我不试图提取一封信时,这些是单词:http://prntscr.com/2vzktn
这是我使用断点时的错误:http://prntscr.com/2vzlr3
这是弄乱的行:“printf(”\ n%s \ n“,temp [0]);”
这是代码:
int main(void)
{
char **dictmat;
char temp[100];
int i = 0, comp, file, found = 0, j = 0, foundmiss = 0;
FILE* input;
dictmat = ReadDict();
/*opens the text file*/
input = fopen("y:\\textfile.txt", "r");
/*checks if we can open the file, otherwise output error message*/
if (input == NULL)
{
printf("Could not open textfile.txt for reading \n");
}
else
{
/*allocates the memory location to the rows using a for loop*/
do
{
/*temp_line is now the contents of the line in the file*/
file = fscanf(input, "%s", temp);
if (file != EOF)
{
lowercase_remove_punct(temp, temp);
for (i = 0; i < 1000; i++)
{
comp = strcmp(temp, dictmat[i]);
if (comp == 0)
{
/*it has found the word in the dictionary*/
found = 1;
}
}
/*it has not found a word in the dictionay, so the word must be misspelt*/
if (found == 0 && (strcmp(temp, "") !=0))
{
/*temp is the variable that is misspelt*/
printf("\n%s \n",temp[0]);
/*checks for a difference of one letter*/
//one_let(temp);
}
found = 0;
foundmiss = 0;
}
} while (file != EOF);
/*closes the file*/
fclose(input);
}
free_matrix(dictmat);
return 0;
}
打印角色时,请使用%c
,而不是%s
。两者之间存在根本区别。后者用于字符串。
当printf遇到%c
时,它会将ASCII格式的一个字节插入到指定变量的输出流中。
当它看到%s
时,它会将变量解释为字符指针,并从变量中指定的地址开始以ASCII格式复制字节,直到遇到包含零的字节。
print char - 不是字符串:
printf("\n%c \n",temp[0]);
temp [0]是一个角色。如果你正在使用这个
printf("\n%s \n",temp[0]);
它将从address i.e. temp[0]
打印字符串。可能是这个位置无法访问,所以它崩溃了。
这改变了
printf("\n%c \n",temp[0]);
为什么使用%s作为修饰符,请使用%c