[英]Extract character from a string bug
我从文件中读取了一个temp变量,这是一个单词,例如“ and”,但是,当我提取第一个字符(例如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格式复制字节,直到遇到一个包含零的字节。
打印字符-不是字符串:
printf("\n%c \n",temp[0]);
temp [0]是一个字符。 因此,如果您使用
printf("\n%s \n",temp[0]);
它将从address ie temp[0]
打印字符串。 可能是无法访问此位置,所以它崩溃了。
将此更改为
printf("\n%c \n",temp[0]);
为什么要使用%s作为修饰符,请使用%c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.