我从一个文件中读入了一个临时变量,这是一个词,例如“和”,但是,当我提取第一个字符时,例如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 格式的字节,直到遇到包含零的字节。
关于c - 从字符串错误中提取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22041859/