c - 在 C 中使用 sscanf 读取带有空格的字符串时,标点符号会导致错误

标签 c whitespace scanf punctuation

更新:使用char string[sizeof buffer - 1]正确初始化字符串已经解决了崩溃问题,但我仍然很好奇有多个标点符号与此有关!

我正在尝试从“某些文本”形式的文件中读取字符串。到目前为止,使用 sscanf 和模式 \"%[^\"]\" 对我来说效果很好,但是当我开始向字符串添加标点符号时,程序已经开始崩溃。

似乎只有在使用多个标点符号时才会出现错误,无论它是什么标点符号或标记的位置。无论文件中带有标点符号的行的位置如何,都会发生这种情况(即,即使最后一行没有标点符号,错误仍然会发生)。

无论如何,下面是我到目前为止的代码:

char* func(char* f_name);
    FILE* file = get_file(f_name,"r"); // a short function I wrote to get the
                                       // file pointer from the current
                                       // directory. The error is almost
                                       // certainly not here.
    if (file == 0) {
        print("Unable to load file\nExiting...");
        exit(-1);
    }

    char* pattern = "\"%[^\"]\"";
    int read_args = -1;
    char* string; //  string size is unknown until read
    char buffer[1200]; // i expect very long line of data in the file

    while ( fgets( buffer, sizeof(buffer), file ) != NULL ) {
        printf("found line: %s\n",buffer);
        read_args = sscanf(buffer, pattern, string);
        printf("num args: %d\n",read_args);
        printf("read value: %s\n", string);
    }

    fclose(file);
    return string;
}

以下是我尝试过的一些数据。在标记为“不成功”的地方,程序会编译、运行所有内容,然后在退出之前崩溃。

"test test test" // successful
"test, test test" // successful
"test test; test" // successful

"test, test, test" // unsuccessful
"test; test. test," // unsuccessful

如果此问题得到解决,我计划使用更复杂的模式,并且正在使用模式 %d\"%[^\"]\"\"%[^\"]\"< 读取数据 在此错误发生之前已成功。预先感谢您的任何答复。

最佳答案

您的代码会调用未定义的行为,因为您正在扫描随机内存。

string 变量从未初始化,因此 sscanf() 写入的字符串的目标未定义。

你需要例如

char string[sizeof buffer - 1];

事实上,它并不总是崩溃只是运气,代码一直在调用未定义的行为。根据您的示例,可能只是使用标点符号,扫描的文本更长,因此覆盖了更多内存,一旦遇到足够重要的内容,最终会触发崩溃。

关于c - 在 C 中使用 sscanf 读取带有空格的字符串时,标点符号会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8863871/

相关文章:

c - 如何在C中成对读取 float ?

c# - 相当于C#中的sscanf_s?

c - 如何计算字符串中未知数量的 float

c++ - 通过位域访问 char 中的位

c - 对 strcmp 感到困惑

javascript - 空间位置在这些跨度中重要吗?

ios - xcode 在分支 merge 后用空格替换制表符

c - 读取空格后的行

将 float 与整数进行比较

mysql - 如何让额外的空格影响我的 MySQL 查询结果?