c - fscanf 帮助 : how to check for formatting

标签 c string buffer scanf

因此当前函数应该看到存储在两个井号之间的任何内容(#abc# 应该返回 abc),但是如果我想错误检查以查看是否缺少井号,或者井号之间没有任何内容,或者两个井号之间的字符串长度大于一定数量的字符,我是否使用 fscanf 函数来做到这一点?

fscanf 代码如下所示:

if (fscanf(fp, " %c%[^#]%c", &start, buffer, &end) == 3) {
    return strdup(buffer);      
} else { 
    return NULL; 

最佳答案

do I use the fscanf function to do that?

不,你不知道。使用 scanf() 系列函数很少是个好主意。

char buf[0x1000];

// expect leading `#'
int ch = fgetc(fp);
if (ch != '#') {
    puts("Error, missing # at beginning of input");
    exit(-1);
}

// read until terminating `#' or until the buffer is exhausted
char *p = buf;
while ((ch = fgetc(fp)) != '#' && p - buf < sizeof(buf)) {
    *p++ = ch;
}

// expect terminating `#'
if (ch != '#') {
    puts("Error, missing # at end of input");
    exit(-1);
}

关于c - fscanf 帮助 : how to check for formatting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15985203/

相关文章:

c - 为什么我们需要 stdin 作为输入函数的文件版本?

java - 字符串索引越界异常 : String index out of range: -3

c - 将变量放在程序不同部分的缓冲区中

c++ - 在 std::vector 中表示原始字节的最佳方式?

php - 数据库迁移后 PHP 在输出缓冲区中有换行符

c++ - 在不同环境中正确使用 C 虚拟函数替换

时间:2019-03-17 标签:c++: TerminateProcess (procHandle,0)

c - 在C中使用printf加载点效果

string - 在 bash 上使用 test 命令比较两个字符串时,由于特殊字符 * 导致出现 "test: too many arguments"消息

c++ - 如何将输入作为空字符串输入?