[英]Extract character from a string bug
I read in a temp variable from a file, this is one word, eg "and", however, when I extract the first character, eg temp[1], the program crashes when running, I have tried break points, and it is on this line. 我从文件中读取了一个temp变量,这是一个单词,例如“ and”,但是,当我提取第一个字符(例如temp [1])时,程序在运行时崩溃,我尝试了断点,并且在这条线上。
This is what happens when I run the code: http://prntscr.com/2vzkmp 这是运行代码时发生的情况: http : //prntscr.com/2vzkmp
These are the words when I don't try to extract a letter: http://prntscr.com/2vzktn 这些是我不尝试提取字母的词: http : //prntscr.com/2vzktn
This is the error when I use breakpoints: http://prntscr.com/2vzlr3 当我使用断点时,这是错误: http : //prntscr.com/2vzlr3
This is the line that is messing up: " printf("\\n%s \\n",temp[0]);" 这是一团糟:“ printf(” \\ n%s \\ n“,temp [0]);”
Here is the code: 这是代码:
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;
}
When printing a character, use %c
, not %s
. 打印字符时,请使用
%c
,而不要使用%s
。 There is a fundamental difference between the two. 两者之间有根本的区别。 The latter is for strings.
后者用于字符串。
When printf encounters a %c
it inserts one byte in ASCII format into the output stream from the variable specified. 当printf遇到
%c
它会将ASCII格式的一个字节从指定的变量插入输出流。
When it sees a %s
it will interpret the variable as a character pointer, and start copying bytes in ASCII format from the address specified in the variable, until it encounters a byte that contains zero. 看到
%s
,它将变量解释为字符指针,并开始从变量中指定的地址开始以ASCII格式复制字节,直到遇到一个包含零的字节。
打印字符-不是字符串:
printf("\n%c \n",temp[0]);
temp[0] is a charater. temp [0]是一个字符。 Thus if you are using
因此,如果您使用
printf("\n%s \n",temp[0]);
it will print the string from address ie temp[0]
. 它将从
address ie temp[0]
打印字符串。 May be this location is not accessible, So it is crashing. 可能是无法访问此位置,所以它崩溃了。
This change it to 将此更改为
printf("\n%c \n",temp[0]);
为什么要使用%s作为修饰符,请使用%c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.