c - 从字符串错误中提取字符

标签 c string file scanf

我从一个文件中读入了一个临时变量,这是一个词,例如“和”,但是,当我提取第一个字符时,例如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/

相关文章:

swift - 如何创建用于写入的文本文件

c# - DirectoryInfo.GetFiles,如何在 C# 中获取不同类型的文件

c - 尝试使用一堆字符串将反向波兰表示法转换为中缀,遇到一个小错误,我不知道是什么原因造成的

C套接字编程接收未知长度的数据

delphi - 如何将字符串中的\xA0(或非ASCII)字符替换为''?

string - SPARQL 字符串范围

c# - 从非托管 dll 中读取变量(结构数组)

c - 解释这个功能

c++ - 如何区分两个 std::set<string> 的元素?

c++ - 将一行文件读入一个对象中的2个变量